如果我有两个长度为M和N的一维数组,最有效的方法是计算所有点之间的欧式距离,得到的结果为NxM数组?我想通过Numpy弄清楚这一点,但它还很陌生,所以有点卡住了。
目前,我正在以这种方式进行操作:
def get_distances(x,y):
#compute distances between all points
distances = np.zeros((len(y),len(x)))
for i in range(len(y)):
for j in range(len(x)):
distances[i,j] = (x[j] - y[i])**2
return distances
假设您具有一维位置:
您可以使用广播:
结果是:
所以i,j索引是数组1的点i与数组2的点j之间的距离
if you want the result to be NxM in shape you need to exchange
a
andb
: