how to calculate the dot product of two arrays of

2019-02-26 20:53发布

问题:

This question already has an answer here:

  • Vectorized way of calculating row-wise dot product two matrices with Scipy 5 answers

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)?

回答1:

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)