2个向量中所有点之间的欧式距离

如果我有两个长度为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
评论
  • det
    det 回复

    假设您具有一维位置:

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

    您可以使用广播:

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

    结果是:

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

    所以i,j索引是数组1的点i与数组2的点j之间的距离

    if you want the result to be NxM in shape you need to exchange a and b:

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