python numpy euclidean distance calculation between matrices of row vectors

python numpy euclidean distance calculation between matrices of row vectors

To get the distance you can use the norm method of the linalg module in numpy:

np.linalg.norm(x - y)

While you can use vectorize, @Karls approach will be rather slow with numpy arrays.

The easier approach is to just do np.hypot(*(points - single_point).T). (The transpose assumes that points is a Nx2 array, rather than a 2xN. If its 2xN, you dont need the .T.

However this is a bit unreadable, so you write it out more explictly like this (using some canned example data…):

import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))

dist = (points - single_point)**2
dist = np.sum(dist, axis=1)
dist = np.sqrt(dist)

python numpy euclidean distance calculation between matrices of row vectors

import numpy as np
def distance(v1, v2):
    return np.sqrt(np.sum((v1 - v2) ** 2))    

Leave a Reply

Your email address will not be published.