简体   繁体   中英

python: Multiply slice i of a matrix stack by column i of a matrix efficiently

import numpy as np
M,N,R = 2,3,4

# For a 3-dimensional array A:
A = np.reshape(np.r_[0:M*N*R], [M,N,R], order = 'C')

# and 2-dimensional array B:
B = np.reshape(np.r_[0:M*R], [R,M], order = 'C')

I would like the N*M matrix that results from multiplying slice i of A by column i of B . I have tried np.dot , and np.einsum and have been unable to obtain what I need.

Could anybody help, please? Thanks!

With np.einsum , we would have -

np.einsum('ijk,ki->ji',A,B)

Let's verify the results using the given sample and using matrix-multiplication with np.dot -

In [35]: A.shape
Out[35]: (2, 3, 4)

In [36]: B.shape
Out[36]: (4, 2)

In [37]: A[0].dot(B[:,0])
Out[37]: array([ 28,  76, 124])

In [38]: A[1].dot(B[:,1])
Out[38]: array([226, 290, 354])

In [39]: np.einsum('ijk,ki->ji',A,B)
Out[39]: 
array([[ 28, 226],
       [ 76, 290],
       [124, 354]])

For aspects related to when to use einsum over dot-based tools like np.dot / np.tensordot , here's a related post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM