简体   繁体   English

IndexError:创建均匀粒子时数组的索引过多

[英]IndexError: too many indices for array while creating uniform particles

I have this function here designed to create uniform particles over given x and y ranges, which are going to be 1x2 matrices.我有这个 function 这里设计用于在给定的 x 和 y 范围内创建均匀的粒子,这将是 1x2 矩阵。 However, when I try and run it, I get the error below.但是,当我尝试运行它时,出现以下错误。 I feel that there is a slicker way to assign the x and y values into my particles matrix.我觉得有一种更巧妙的方法可以将 x 和 y 值分配到我的粒子矩阵中。 How can I solve this?我该如何解决这个问题?

def create_uniform_particles(x_range, y_range, N):
    particles = np.empty((N, 2))
    new_x = uniform(x_range[0], x_range[1], size=(N,1))
    new_y = uniform(y_range[0], y_range[1], size=(N,1))
    for i in range(N):
        particles[i][0] = new_x[i]
        particles[i][1] = new_y[i]
    return particles

#Error: #错误:

Traceback (most recent call last):
  File "/Users/scottdayton/PycharmProjects/Uncertainty Research/particle.py", line 83, in <module>
    particle_filter(init, sigma, obs, n, trans, sigma0)
  File "/Users/scottdayton/PycharmProjects/Uncertainty Research/particle.py", line 49, in particle_filter
    particles = create_uniform_particles(new_x_range, new_y_range, n)
  File "/Users/scottdayton/PycharmProjects/Uncertainty Research/particle.py", line 8, in create_uniform_particles
    new_x = uniform(x_range[0], x_range[1], size=(N,1))
IndexError: too many indices for array

Your code for this function appears to be correct (at least, it works for me without any modifications) when I do:当我这样做时,您的 function 代码似乎是正确的(至少,它对我有用,无需任何修改):

create_uniform_particles([0,1],[2,3],5)

I recommend verifying that the variables in the function one level above create_uniform_particles (wherever you set up new_x_range and new_y_range) are the shapes you were expecting.我建议验证 function 中的变量是否比 create_uniform_particles 高一级(无论您在哪里设置 new_x_range 和 new_y_range)都是您期望的形状。 Since this function you wrote works for inputs correctly passed in, it's probably happening somewhere around there.由于您为正确传入的输入编写的 function 作品,它可能发生在附近的某个地方。

In terms of assigning the x's and y's, you can use hstack to concatenate the new_x and new_y vectors together into an array.在分配 x 和 y 方面,您可以使用 hstack 将 new_x 和 new_y 向量连接在一起形成一个数组。 Give this below a try if you like it better.如果您更喜欢它,请在下面尝试一下。 As a side note, the alternative to hstack is vstack, which will concatenate them after each other instead of "next to" each other in your case.作为旁注,hstack 的替代方案是 vstack,它将它们彼此连接起来,而不是在您的情况下彼此“相邻”。

import numpy as np
from numpy.random import uniform

def create_uniform_particles(x_range, y_range, N):
    particles = np.empty((N, 2))
    new_x = uniform(x_range[0], x_range[1], size=(N,1))
    new_y = uniform(y_range[0], y_range[1], size=(N,1))
    return np.hstack([new_x,new_y])

create_uniform_particles([0,1],[2,3],5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM