piton_hunter piton_hunter - 1 month ago 15
Python Question

Column-by-row multiplication in numpy

I have 2 matrices

A
(
mxn
) and
B
(
nxm
). I would to get matrix
C
(
nxmxm
), such that
C[i]=A[:, i].dot(B[i, :])
. In other words I would like to get matrix, where first element is dot of first column of
A
and first row of
B
, second element is dot of second column of
A
and second row of
B
, etc.
For example for such
A
and
B


A = np.array([[1, 2, 3], [0, 1, -1]])
B = np.array([[4, 5], [6, 7], [8, 9]])


I would like to have such matrix:

C = np.array([[[4, 5], [0, 0]],
[[12, 14], [6, 7]],
[[24, 27], [-8, -9]]])


Is it possible without cycles? If not, is it possible for case A = B.T?

Answer

You can use np.einsum:

np.einsum('ij,jk->ijk', A, B)

array([[[ 4,  5],
        [12, 14],
        [24, 27]],

       [[ 0,  0],
        [ 6,  7],
        [-8, -9]]])

EDIT

From your comment:

np.einsum('ij,jk->jik', A, B)

will give you the desired shape of C