1

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?

0

1 Answer 1

3

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is it faster than double loop?
The code is vectorized, so it should be faster. But the best remains to test yourself on your dataset ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.