Get min and max distance withing a point cloud
Here we will learn how to find the maximal or minimal distance between two points in a cloud of points. To do so, we will use the pdist
function available in the scipy.spatial.distance
package.
This function computes the pairwise distances between observations in n-dimensional space; in order to find the longest or shortest distance, juste take the max or min.
import numpy as np
from scipy.spatial.distance import pdist
points = np.random.random((10,3)) #generate 100 points
pairwise = pdist(points) # compute the pairwise distance between those points
#compute the maximal and minimal distance
print(f"maximal distance : {np.max(pairwise)}")
print(f"minimal distance : {np.min(pairwise)}")
maximal distance : 1.1393617436726384
minimal distance : 0.2382615513731064
The pdist function can that different metric for the distance computation. The default metrics are : * braycurtis * canberra * chebyshev * cityblock * correlation * cosine * dice * euclidean * hamming * jaccard * jensenshannon * kulsinski * mahalanobis * matching * minkowski * rogerstanimoto * russellrao * seuclidean * sokalmichener * sokalsneath * sqeuclidean * yule
You can also define your own distances with a lambda function
np.max(pdist(points, lambda u, v: np.sqrt(((u-v)**2).sum())))
1.1393617436726384
or with a classical function
def dfun(u, v):
return np.sqrt(((u-v)**2).sum())
np.max(pdist(points, dfun))
1.1393617436726384