Python Forum

Full Version: matrix multiplication term by term
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following numpy arrays:
A of size (MxK)
B of size (MxN)

How to multiply A and B to get a matrix of size (MxKxN)?

I tried with A * B and somebody suggested A[:,None]*B. But that doesn't give what I need.

To be clear, I want to generate c[i,j,k] = a[i,j]*b[i,k].

I apologize that the question is somewhat basic, as I am a beginner.
I think np.einsum('ij,ik->ijk', a, b) does the trick
import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.array([[7, 8], [9, 10], [11, 12]])

print('='*20)
print('a =\n', a)
print()
print('b =\n', b)
print()
result = np.einsum('ij,ik->ijk', a, b)
print('result =\n', result)

spam = [[[
    a[i,j]*b[i,k] for k in range(2)]
        for j in range(2)]
            for i in range(3)]

print(np.array_equal(spam, result))
Output:
==================== a = [[1 2] [3 4] [5 6]] b = [[ 7 8] [ 9 10] [11 12]] result = [[[ 7 8] [14 16]] [[27 30] [36 40]] [[55 60] [66 72]]] True