2个向量中所有点之间的欧几里德距离 [英] Euclidean Distance Between All Points in an 2 Vectors

查看:54
本文介绍了2个向量中所有点之间的欧几里德距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个长度为 M 和 N 的一维数组,计算所有点之间的欧氏距离的最有效方法是什么,结果是 NxM 数组?我正在尝试用 Numpy 解决这个问题,但我对它很陌生,所以我有点卡住了.

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? I'm trying to figure this out with Numpy but am pretty new to it so I'm a little stuck.

目前我是这样做的:

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 :

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 之间的距离

So the i, j index is the distance between point i from array 1 and point j of array 2

如果你希望结果是 NxM,你需要交换 ab:

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

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

这篇关于2个向量中所有点之间的欧几里德距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆