我有几个粒子的2D位置(x,y)的数组。在Mathematica中,如果pos
是一个形状为(n,2)
的数组,其中n
是粒子的数量,那么我可以使用Outer[Subtract, pos, pos, 1]
,上面的数学代码的结果是一个n x n x 2
数组,这个矩阵的每个i,j元素都是(x_i - x_j, y_i - y_j)
运算的结果。
例如
pos = {{x1, y1}, {x2, y2}, {x3, y3}};
Outer[Subtract, pos, pos, 1]
给出
{
{{0, 0}, {x1 - x2, y1 - y2}, {x1 - x3, y1 - y3}}
,
{{-x1 + x2, -y1 + y2}, {0, 0}, {x2 - x3, y2 - y3}}
,
{{-x1 + x3, -y1 + y3}, {-x2 + x3, -y2 + y3}, {0, 0}}
}
它是一个3x3x2的阵列。然而,在python中,我无法获得类似的结果:
import numpy as np
pos = [[1, 2], [5, 6], [8, 9]]
print (np.subtract.outer(pos, pos).shape)
给出(3, 2, 3, 2)
,而np.subtract.outer(pos, pos)
是
array([[[[ 0, -1],
[-4, -5],
[-7, -8]],
[[ 1, 0],
[-3, -4],
[-6, -7]]],
[[[ 4, 3],
[ 0, -1],
[-3, -4]],
[[ 5, 4],
[ 1, 0],
[-2, -3]]],
[[[ 7, 6],
[ 3, 2],
[ 0, -1]],
[[ 8, 7],
[ 4, 3],
[ 1, 0]]]])
而对于类似的值,Mathemtica代码给出了我所需要的,即
{
{{0, 0}, {-4, -4}, {-7, -7}}
,
{{4, 4}, {0, 0}, {-3, -3}}
,
{{7, 7}, {3, 3}, {0, 0}}
}
发布于 2018-08-06 06:11:03
您正在寻找:
pos = np.array(pos)
pos[:,None]-pos
您也可以通过以下方式实现相同的目的:
np.squeeze([i-pos for i in pos])
编辑:
对于标准化,您可以执行以下操作:
ss = np.linalg.norm(pos_diff,axis = 2,keepdims = True)
ss[ss==0] = 1
pos_diff/ss
发布于 2018-08-06 05:51:05
numpy.ufunc.outer(a,b)
将计算每个可能的组合,其中一个元素来自a
,另一个元素来自b
。一种方法是分别计算x和y坐标,然后重新合并result
pos = np.array([[1, 2], [5, 7], [8, 13]])
dx = np.subtract.outer(pos[:,0],pos[:,0])
dy = np.subtract.outer(pos[:,1],pos[:,1])
result=np.transpose([dx,dy], axes=(1,2,0))
(我更改了pos
中的值,以便结果不那么对称。)
编辑:与在整个数组上执行subtract.outer
,然后在之后使用squeeze
来计算和存储无用的x_i-y_j相比,这种解决方案对于大型数组来说要有效得多。
https://stackoverflow.com/questions/51698356
复制相似问题