How do I calculate all pairs of vector differences in numpy?

落爺英雄遲暮 提交于 2019-12-01 18:38:11

You can use broadcasting after extending the dimensions with None/np.newaxis to form a 3D array version of x and subtracting the original 2D array version from it, like so -

x[:, np.newaxis, :] - x

Sample run -

In [6]: x
Out[6]: 
array([[6, 5, 3],
       [4, 3, 5],
       [0, 6, 7],
       [8, 4, 1]])

In [7]: x[:,None,:] - x
Out[7]: 
array([[[ 0,  0,  0],
        [ 2,  2, -2],
        [ 6, -1, -4],
        [-2,  1,  2]],

       [[-2, -2,  2],
        [ 0,  0,  0],
        [ 4, -3, -2],
        [-4, -1,  4]],

       [[-6,  1,  4],
        [-4,  3,  2],
        [ 0,  0,  0],
        [-8,  2,  6]],

       [[ 2, -1, -2],
        [ 4,  1, -4],
        [ 8, -2, -6],
        [ 0,  0,  0]]])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!