6

A and B are both arrays with shape(N,3). They each contain N vectors such that A[0] = a0 (vector), A[1] = a1... and B[0] = b0, B[1] = b1...

I want to calculate the dot product of the N pairs of vectors an and bn. In other words, I want to obtain an array C with shape(N,1) such that C[i] = np.dot(A[i],B[i]). What is the most efficient way of doing this in python (e.g. using vectorized code)?

Jorel Amthor
  • 1,264
  • 13
  • 38
Physicist
  • 2,848
  • 8
  • 33
  • 62
  • For a physicist there's a surprising amount of hand waving in this problem description. What have you tried, vectorized or not? Small sample arrays would be nice. The numpy dot tools are `np.dot`, `np.tensordot`, `np.einsum`, and the new `@`. – hpaulj Jan 29 '16 at 17:39
  • In case someone comes here 7 years after the question was asked the einsum idea is a good one but I find the documentation a bit confusing. I had the exact same problem: the inner product of N vectors row by row. To do this with einsum I found this to work `np.einsum('...j,...j',A,B)` – Goffredo Bosco Mar 01 '23 at 19:44

1 Answers1

11

You can perform element-wise multiplication and then sum along the second axis, like so -

C = (A*B).sum(1)

These multiplication and summation operations can be implemented in one go with np.einsum, like so -

C = np.einsum('ij,ij->i',A,B)

With np.matmul/@-operator -

(A[:,None,:] @ B[...,None]).ravel()
Divakar
  • 218,885
  • 19
  • 262
  • 358