简体   繁体   中英

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

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 :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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