In Numpy, find Euclidean distance between each pair from two arrays

LWZ picture LWZ · Jul 30, 2013 · Viewed 14.1k times · Source

I have two arrays of 2D coordinate points (x,y)

a = [ (x1,y1), (x2,y2), ... (xN,yN) ]
b = [ (X1,Y1), (X2,Y2), ... (XN,YN) ]

How can I find the Euclidean distances between each aligned pairs (xi,yi) to (Xi,Yi) in an 1xN array?

The scipy.spatial.cdist function gives me distances between all pairs in an NxN array.

If I just use norm function to calculate the distance one by one it seems to be slow.

Is there a built in function to do this?

Answer

user2357112 supports Monica picture user2357112 supports Monica · Jul 30, 2013

I'm not seeing a built-in, but you could do it yourself pretty easily.

distances = (a-b)**2
distances = distances.sum(axis=-1)
distances = np.sqrt(distances)