This question already has an answer here:
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)?
You can perform element-wise multiplication and then sum along the second axis, like so -
These multiplication and summation operations can be implemented in one go with
np.einsum
, like so -