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
.