I have two numpy arrays with n number of coordinates (two items per row).
coords_a = np.random.random((20, 2))
coords_b = np.random.random((20, 2))
Now, for each combination of rows, I want to compute a function and save the return value as item in a matrix. The resulting array should therefore have shape (20, 20) and can be "lazily" computed as shown below. As exemplary function, the Euclidean distance is used.
def euclidean_dist(x1: float, y1: float, x2: float, y2: float) -> float:
"""Return the euclidean distance between two the points (x1, y1) and (x2, y2)."""
return np.sqrt(np.square(x1 - x2) + np.square(y1 - y2))
matrix = []
for a in coords_a:
row = []
for b in coords_b:
row.append(euclidean_dist(*a, *b))
matrix.append(row)
matrix = np.array(matrix)
As you can imagine, this nested for loop is very time consuming taking over 25 seconds with just 2000 coordinate pairs. Is there a recommended way of vectoring this sort of cross product?
Thanks in advance.