Add Two Matrices in Python

(Last Updated On: 06/01/2023)

Python Program to Add Two Matrices Using for Loop

# Python Program to Add Two Matrices Using for Loop

X = [[1, 6, 4],
     [7, 2, 9],
     [5, 8, 3]]

Y = [[8, 3, 5],
     [2, 7, 0],
     [4, 1, 6]]

res = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

# rows iteration
for i in range(len(X)):
    # columns iteration
   for j in range(len(X[0])):
       res[i][j] = X[i][j] + Y[i][j]

for i in res:
   print(i)

Output:

[9, 9, 9]
[9, 9, 9]
[9, 9, 9]

Leave a Reply

Your email address will not be published. Required fields are marked *