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?
CodePudding user response:
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]])