Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get distances between 2 xyz numpy arrays without loop?

Suppose I have 2 numpy arrays containing xyz coordinates of points. Each point’s coordinates is a row.

a
[0 1 0]
[3 1 0]
[0 0 3]
[3 4 0]
[0 2 0]
[2 3 4]
[0 1 2]
[0 3 2]
b
[1 1 2]
[1 1 2]
[0 2 2]
[4 2 1]
[4 4 4]

Is it possible to calculate the distance (sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)) from each point of a to each point of b without a double for loop?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use scipy.distance.spatial.cdist:

from scipy.spatial.distance import cdist

out = cdist(a, b)

NB. by default, the distance is euclidean but you have other metrics (see the doc)

output (a.shape[0] x b.shape[0]):

array([[2.23606798, 2.23606798, 2.23606798, 4.24264069, 6.40312424],
       [2.82842712, 2.82842712, 3.74165739, 1.73205081, 5.09901951],
       [1.73205081, 1.73205081, 2.23606798, 4.89897949, 5.74456265],
       [4.12310563, 4.12310563, 4.12310563, 2.44948974, 4.12310563],
       [2.44948974, 2.44948974, 2.        , 4.12310563, 6.        ],
       [3.        , 3.        , 3.        , 3.74165739, 2.23606798],
       [1.        , 1.        , 1.        , 4.24264069, 5.38516481],
       [2.23606798, 2.23606798, 1.        , 4.24264069, 4.58257569]])

used input:

a = np.array([[0, 1, 0], [3, 1, 0], [0, 0, 3], [3, 4, 0], [0, 2, 0], [2, 3, 4], [0, 1, 2], [0, 3, 2]])
b = np.array([[1, 1, 2], [1, 1, 2], [0, 2, 2], [4, 2, 1], [4, 4, 4]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading