Euclidian Distances between points

I have an array of points in numpy:

points = rand(dim, n_points)

I want too:

  • Calculate the whole norm l2 (Euclidean distance) between a certain point and all other points
  • Calculate all pairwise distances.

and preferably all numpy and no for. How can I do that?

+3
source share
2 answers

If you want to use SciPy, the module scipy.spatial.distance(functions cdistand / or pdist) does exactly what you want with all the loops executed in C. You can do this using translation too, but there is an additional additional memory overhead.

+4
source

This may help with the second part:

import numpy as np
from numpy import *
p=rand(3,4) # this is column-wise so each vector has length 3
sqrt(sum((p[:,np.newaxis,:]-p[:,:,np.newaxis])**2 ,axis=0) )

which gives

array([[ 0.        ,  0.37355868,  0.64896708,  1.14974483],
   [ 0.37355868,  0.        ,  0.6277216 ,  1.19625254],
   [ 0.64896708,  0.6277216 ,  0.        ,  0.77465192],
   [ 1.14974483,  1.19625254,  0.77465192,  0.        ]])

if p was

array([[ 0.46193242,  0.11934744,  0.3836483 ,  0.84897951],
   [ 0.19102709,  0.33050367,  0.36382587,  0.96880535],
   [ 0.84963349,  0.79740414,  0.22901247,  0.09652746]])

sqrt(sum ((p[:,0]-p[:,2] )**2 ))
0.64896708223796884

, newaxis, .

!

+1

Source: https://habr.com/ru/post/1737811/


All Articles