Javaexercise.com

Updated On 2021-09-24 20:55:46

Python Program To Multiply Two Matrix

A matrix is a list of lists in Python that represents data into rows and columns. We can multiply one matrix with another matrix with the help of loops. Let's see some examples.

Matrix Multiplication Program in Python

# Python Program to Multiply Two Matrix
# First Matrix
A =  [[20, 10], [5, 6]]
# Second Matrix
B = [[10, 20], [7, 4]]
# Third Matrix to store result
Z = [[0, 0], [0, 0]]
# Iterate First Matrix row-wise
for i in range(len(A)):
 # Iterate Second Matrix column-wise
 for j in range(len(B[0])):
   # Iterate Second Matrix row-wise
   for k in range(len(B)):
     Z[i][j] += A[i][k] * B[k][j]
print("Multiplication of Two Matrices")
for r in Z:
 print(r)

Output:

Multiplication of Two Matrices
[270, 440]
[92, 124]

 

Python Program for Matrix Multiplication

# Python Program to Multiply Two Matrix
# First Matrix
A =  [[20, 10], [5, 6]]
# Second Matrix
B = [[10, 20], [7, 4, 10]]
# Third Matrix to store result
Z = [[0, 0], [0, 0]]
# Iterate First Matrix row-wise
for i in range(len(A)):
 # Iterate Second Matrix column-wise
 for j in range(len(B[0])):
   # Iterate Second Matrix row-wise
   Z = [[sum(a * b for a, b in zip(A_row, B_col))  
                        for B_col in zip(*B)] 
                                for A_row in A]
print("Multiplication of Two Matrices")
for r in Z:
 print(r)

Output:

Multiplication of Two Matrices
[270, 440]
[92, 124]