;

Python Program to Multiply Two Matrices


Tutorialsrack 23/04/2020 Python

In this Python program, we will learn how to multiply two matrices. 

Here is the code of the program to multiply two matrices.

Program 1: Program to multiply two matrices using nested For loops

Program to multiply two matrices using nested For loops
# Program to multiply two matrices using nested For loops

# 3x3 matrix
X = [[6,7,3],
    [4 ,11,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# Output is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

print("\nOutput of Multiplication of Two Matrices:")
for r in result:
   print(r)
Output

Output of Multiplication of Two Matrices:

[84, 112, 54, 15]

[110, 139, 91, 14]

[119, 157, 112, 23]

Program 2: Program to multiply two matrices using list comprehension

Program to multiply two matrices using list comprehension
# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[6,7,3],
    [4 ,11,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# Output is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]

print("\nOutput of Multiplication of Two Matrices:")
for r in result:
   print(r)
Output

Output of Multiplication of Two Matrices:

[84, 112, 54, 15]

[110, 139, 91, 14]

[119, 157, 112, 23]


Related Posts



Comments

Recent Posts
Tags