Let v, u be the 3D-coordinate matrices of shapes (n, 3) and (m, 3), respectively.
I want to compute the matrix M of shape (n, m) such that M[i, j] = ||v[i] - u[j]|| -- the second vector norm. The task can be solved via cycle:
n, m = 100, 200
M = np.zeros((n, m))
v = np.random.rand(n, 3)
г = np.random.rand(m, 3)
for i in range(n):
for j in range(m):
M[i, j] = np.linalg.norm(v[i] - u[j], ord=2)
Instead, how can I do that in vectorized way in numpy?
You can vectorize by taking advantage of array broadcasting (see https://numpy.org/doc/stable/user/basics.broadcasting.html). If array
vhas shape(n, 1, 3), and arrayuhas shape(m, 3), the array that results from applying an arithmetic operation likev - uwill have shape(n, m, 3). You can then apply the linalg norm operation along an axis by specifying the axis in the call tonp.linalg.normThis has a massive speedup, as you might expect.
It takes some time to get used to array broadcasting, but that's just practice.