简体   繁体   English

2个向量中所有点之间的欧几里德距离

[英]Euclidean Distance Between All Points in an 2 Vectors

If I have two single-dimensional arrays of length M and N what is the most efficient way to calculate the euclidean distance between all points with the resultant being an NxM array?如果我有两个长度为 M 和 N 的一维数组,计算所有点之间的欧几里德距离的最有效方法是什么,结果是 NxM 数组? I'm trying to figure this out with Numpy but am pretty new to it so I'm a little stuck.我试图用 Numpy 解决这个问题,但我对它很陌生,所以我有点卡住了。

Currently I am doing it this way:目前我是这样做的:

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

Suppose you have 1-dimensional positions :假设您有 1 维位置:

a = np.random.uniform(50,200,5)
b = np.random.uniform(50,200,3)

you can just use broadcasting:你可以只使用广播:

result = np.abs(a[:, None] - b[None, :])

with the result being:结果是:

array([[ 44.37361012,  22.20152487,  89.04608885],
       [ 42.83825434,  20.66616909,  87.51073307],
       [  0.19806059,  21.97402467,  44.87053932],
       [  8.42276237,  13.74932288,  53.0952411 ],
       [  8.12181467,  30.29389993,  36.55066406]])

So the i, j index is the distance between point i from array 1 and point j of array 2所以 i, j 索引是数组 1 的点 i 和数组 2 的点 j 之间的距离

if you want the result to be NxM in shape you need to exchange a and b :如果您希望结果为 NxM,则需要交换ab

result = np.abs(b[:, None] - a[None, :])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM