Numpy two matrices, pairwise dot product of rows

9.5k views Asked by At

We are currently working on a python project and have to vectorize a lot due to performance constraints. We end up with the following calculation: We have two numpy arrays of shape (20,6) and want to calculate the pairwise dot product of the rows, i.e. we should obtain a (20,1) matrix in the end, where each row is the scalar obtained by the respective vector dot multiplication.

1

There are 1 answers

1
Psidom On

You can multiply the two arrays element wise and then do sum by rows, and then you have an array where each element is a dot product from rows of the two original arrays:

a = np.array([[1,2], [3,4]])
b = np.array([[3,4], [2,1]])

(a * b).sum(axis=1)
# array([11, 10])