本文介绍了如何计算numpy中的所有向量差对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以做np.subtract.outer(x, x).如果x具有形状(n,),那么我最终得到形状为(n, n)的数组.但是,我有一个形状为(n, 3)x.我想输出形状为(n, n, 3)的东西.我该怎么做呢?也许np.einsum?

I know I can do np.subtract.outer(x, x). If x has shape (n,), then I end up with an array with shape (n, n). However, I have an x with shape (n, 3). I want to output something with shape (n, n, 3). How do I do this? Maybe np.einsum?

推荐答案

您可以使用 None/np.newaxis 形成x的3D阵列版本,并从中减去原始2D阵列版本,就像这样-

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

样品运行-

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

这篇关于如何计算numpy中的所有向量差对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:09