Change language

Python program for multiplying two matrices

|

Examples:

 Input: X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1 , 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output: [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111 , 21] 

Using Simple Nested Loops
In this program, we must use nested for loops to iterate over each row and each column.

# Program for multiplying two matrices using nested loops

 
# take a 3x3 matrix

A = [[ 12 , 7 , 3 ],

[ 4 , 5 , 6 ],

[ 7 , 8 , 9 ]]

 
# take a 3x4 matrix

B = [[[ 5 , 8 , 1 , 2 ],

[ 6 , 7 , 3 , 0 ],

[ 4 , 5 , 9 , 1 ]]

 

result = [[[ 0 , 0 , 0 , 0 ],

[ 0 , 0 , 0 , 0 ],

[ 0 , 0 , 0 , 0 ] ]

 
# iterate over line A

for i in range ( len (A)):

 

# iterate over the column by B

for j in range ( len (B [ 0 ])):

 

# iterate over lines B

  for k in range ( len (B)):

  result [i] [j] + = A [i] [k] * B [k] [j]

 

for r in result:

print (r)

Output:

 [114, 160, 60, 27] [74 , 97, 73, 14] [119, 157, 112, 23] 

Method 2: Matrix multiplication using a nested list. We are using

# Program for multiplying two matrices using a list

 
# take a 3x3 matrix

A = [[ 12 , 7 , 3 ],

[ 4 , 5 , 6 ],

[ 7 , 8 , 9 ]]

 
# take a 3x4 matrix

B = [[ 5 , 8 , 1 , 2 ],

[ 6 , 7 , 3 , 0 ],

  [ 4 , 5 , 9 , 1 ]]

 
# the result will be 3x4

result = [[ sum (a * b for a, b in zip (A_row, B_col) ) 

for B_col in zip ( * B)]

  for A_row in A]

 

for r in result:

print (r)

Output:

 [114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically