I am trying to find the Euclidean distance between sets of coordinates and a fixed point.
I have MxN sets of x,y,z coordinates and I want to find the distance between them and a fixed x,y,z coordinate.
I know I can use a couple of for loops to iterate through and calculate the distances 1 by 1 using scipy.spatial.distance.euclidean, but this ends up taking a long time when the number of coordinates becomes large (e.g. 100x40). Is there a way I can do this more efficiently?
Very brief example for obchardon
c = np.array([[[1,2,3],[4,5,6,]],[[1,1,1],[2,2,2]],[[6,5,4],[2,3,1]]])
# shape = (3,2,3) so 3x2 sets of x,y,z coords, so desire 3x2=6 sets of distances
s = np.array([[0],[0],[1]])
DISTANCEFUNC(c,s) -> 3x2 sets of euclidean distances
CodePudding user response:
You can use np.linalg.norm
:
import numpy as np
coords = np.random.rand(M, N, 3) # Your sets of coordinates here
fixed = np.random.rand(3) # Fixed coordinate
distances = np.linalg.norm(coords - fixed, axis=2)
# shape (M, N) of distances