1

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.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Sleik
  • 341
  • 4
  • 11

1 Answers1

10

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])
Psidom
  • 209,562
  • 33
  • 339
  • 356