python中的“outer”类似于Mathematica内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (180)

``````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}}
}
``````

``````import numpy as np
pos = [[1, 2], [5, 6], [8, 9]]
print (np.subtract.outer(pos, pos).shape)
``````

``````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]]]])
``````

``````{
{{0, 0}, {-4, -4}, {-7, -7}}
,
{{4, 4}, {0, 0}, {-3, -3}}
,
{{7, 7}, {3, 3}, {0, 0}}
}
``````

2 个回答

``````pos = np.array(pos)

pos[:,None]-pos
``````

``````np.squeeze([i-pos for i in pos])
``````

`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`使结果不那么对称。）