Python Forum
matrix multiplication term by term
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
matrix multiplication term by term
#1
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.
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The term 'pip' is not recognized as the name of a cmdlet, function michaelnicol 1 636 Jul-16-2023, 11:12 PM
Last Post: deanhystad
  Check if two matrix are equal and of not add the matrix to the list quest 3 839 Jul-10-2023, 02:41 AM
Last Post: deanhystad
  Sum of changing general term Vantin19 2 716 Apr-04-2023, 08:22 AM
Last Post: Gribouillis
  Multiplication Table code alexsendlegames100 3 1,380 Jun-06-2022, 09:45 AM
Last Post: Gribouillis
  Try to solve GTG multiplication table problem. Frankduc 6 2,024 Jan-18-2022, 08:26 PM
Last Post: Frankduc
  Long-term stable source to get news headlines with Python? sandufi 4 1,944 Dec-23-2021, 09:48 AM
Last Post: sandufi
  Need help with my Python code (Multiplication) NeedHelpPython 2 1,690 Oct-04-2021, 12:09 PM
Last Post: Pedroski55
  How to multiply a matrix with herself, until the zero matrix results peanutbutterandjelly 3 3,384 May-03-2021, 06:30 AM
Last Post: Gribouillis
  List conversion and multiplication johnkyp 5 3,176 Jan-02-2020, 08:20 AM
Last Post: perfringo
  Matrix Multiplication Issue VIJENDRA 1 1,873 Dec-19-2019, 06:16 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020