array of minimum euclidian distances between all points in array

3k views Asked by At

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 to get an array of all minimum distances. So for point 1 (x1, y1), I want the distance of the point closest to it, same for point 2 (x2,y2), etc... Distance being sqrt((x1-x2)^2 + (y1-y2)^2).

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

Any concise way of doing this without resorting to loops?

1

There are 1 answers

0
cel On BEST ANSWER

This solution really focuses on readability over performance - It explicitly calculates and stores the whole n x n distance matrix and therefore cannot be considered efficient.

But: It is 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)