I have 2 matrices. I have to calculate the euclidean distance between every row of matrix A and every row of matrix B.
In the first solution I loop over the rows of the two matrices and for each row in matrix A, I take a row from B, take the square of the element wise subtraction, then sum it and take the square root.
I end up with a matrix of the size #rows in A x #rows in B:
import numpy as np A = np.random.random((50, 3072)) B = np.random.random((500, 3072)) # First solution d = np.zeros((50, 500)) for i in range(50): for j in range (500): d[i,j] = np.sqrt(np.sum(np.square(B[j] - A[i])))
In the second solution I did this by broadcasting, and it works. But when I increase the amount of rows in A and B ... it becomes very very slow. Is there a faster way without looping?
# Second solution test = np.sqrt(np.sum(np.square(A[:,np.newaxis]-B),axis=2)) #print check print np.unique(test==d)