在没有循环的numpy中计算xi-xj矩阵(通过api调用)

gro*_*ine 2 python numpy matrix vectorization

如何在没有循环的numpy中计算xi-xj矩阵(通过api调用)?

这是从什么开始:

import numpy as np
x = np.random.rand(4)
xij = np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)
Run Code Online (Sandbox Code Playgroud)

Ale*_*ley 5

您可以利用广播xx平面数组中减去列向量并生成矩阵.

>>> x = np.random.rand(4)
Run Code Online (Sandbox Code Playgroud)

然后:

>>> x - x[:,np.newaxis]
array([[ 0.        ,  0.89175647,  0.80930233,  0.37955823],
       [-0.89175647,  0.        , -0.08245415, -0.51219825],
       [-0.80930233,  0.08245415,  0.        , -0.4297441 ],
       [-0.37955823,  0.51219825,  0.4297441 ,  0.        ]])
Run Code Online (Sandbox Code Playgroud)

如果你想要一个矩阵对象(而不是默认的数组对象),你可以写:

np.matrix(x - x[:,np.newaxis])
Run Code Online (Sandbox Code Playgroud)