当我创建一个numpy数组时,形状通常与我预期的不同。我不知道自己错了什么,请指出我正确的方向。
例如:
theta = np.random.rand(n , 1)*2 *np.pi
theta.round(3)
Out[283]:
array([[ 0.827],
[ 0.951],
[ 5.371],
[ 0.889]])
从theta我想创建一个带有速度矢量分量的数组(nx2数组)...我尝试了几个,但总是得到错误的形状,如果我重塑它的话会有效,但我当然应该能够直奔那里。
velocity = x和y的数组,其中x = v * cos(theta)和y = v * sin(theta)
velocity.reshape(n, 2)
Out[281]:
array([[ 1.16966072, -0.22284058],
[-0.35621286, 0.7848923 ],
[ 0.26813019, -1.17912768],
[-1.14591116, 0.90771365]])
我尝试了几种构建数组的方法。很明显,我已经接近了,但不是很正确。
velocity = np.array((np.cos(theta) * v, np.sin(theta)*v), dtype=float)
velocity
Out[279]:
array([[[ 1.16966072],
[-0.22284058],
[-0.35621286],
[ 0.7848923 ]],
[[ 0.26813019],
[-1.17912768],
[-1.14591116],
[ 0.90771365]]])
velocity.shape
Out[280]: (2, 4, 1)
velocity = np.array([[np.cos(theta)* v],[np.sin(theta)* v]],dtype = float)
velocity
Out[274]:
array([[[[ 1.16966072],
[-0.22284058],
[-0.35621286],
[ 0.7848923 ]]],
[[[ 0.26813019],
[-1.17912768],
[-1.14591116],
[ 0.90771365]]]])
velocity.shape
Out[275]: (2, 1, 4, 1)
velocity = np.dstack((np.cos(theta) * v, np.sin(theta)*v))
velocity
Out[268]:
array([[[ 1.16966072, 0.26813019]],
[[-0.22284058, -1.17912768]],
[[-0.35621286, -1.14591116]],
[[ 0.7848923 , 0.90771365]]])
velocity.shape
Out[269]: (4, 1, 2)
答案 0 :(得分:0)
theta
是(n,1)
np.array([theta, theta])
是(2, n, 1)
。也就是说,np.array
沿着新轴连接2个组件数组,因此是最初的2。
np.array([[theta], [theta]])
将每个theta
换成[] , so each is
(1,n,1), and together
(2,1,n,1)`。
如果需要(n,2),则需要在第二轴上连接。例如:
velocity = np.concatenate([np.cos(theta) * v, np.sin(theta)*v], axis=1)
hstack
和column_stack
也会这样做,以及c_
。
如果您已将theta
创建为(n,)
(1d而不是2),则stack
可能已用于在新的第2轴上加入它们:
velocity = np.stack([np.cos(theta) * v, np.sin(theta)*v], axis=1)
或np.array([...]).T
,即制作一个(2,n)并转置它。
将两个n
元素数组连接到(n,2)数组有很多种方法。即使是np.squeeze(np.array(....)).T
,也要从(2,n,1)中删除1。