how to calculate the dot product of two arrays of

2019-02-26 20:58发布

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

1条回答
混吃等死
2楼-- · 2019-02-26 21:24

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)
查看更多
登录 后发表回答