Array of minimum Euclidean distances between all points in the array

I have this numpy array with points, something like

[(x1,y1), (x2,y2), (x3,y3), (x4,y4), (x5,y5)]

      

What I would like to do is get an array of all minimum distances. So for point 1 (x1, y1)

, I want the distance to the closest point to it, same for point 2 (x2,y2)

, etc ... Distance sqrt((x1-x2)^2 + (y1-y2)^2)

.

This will obviously be an array with the same length as my dotted array (in this case: 5 points -> 5 minimum distances).

Any concise way to do this without resorting to loops?

+3


source to share


1 answer


This solution really focuses on performance readability - it explicitly computes and stores the entire distance matrix n x n

and therefore cannot be considered efficient.

But: It's very concise and readable.



import numpy as np
from scipy.spatial.distance import pdist, squareform

#create n x d matrix (n=observations, d=dimensions)
A = np.array([[1,9,2,4], [1,2,3,1]]).T

# explicitly calculate the whole n x n distance matrix
dist_mat = squareform(pdist(A, metric="euclidean"))

# mask the diagonal
np.fill_diagonal(dist_mat, np.nan)

# and calculate the minimum of each row (or column)
np.nanmin(dist_mat, axis=1)

      

+5


source







All Articles