Python Program to Add Two Matrices – 2024

Hey guys, in this blog we will see a Python Program to Add Two Matrices.

Code

# Python Program to Add Two Matrices

X = [[2,3,3],
    [14,5,7],
    [5,18,19]]

Y = [[8,1,3],
    [1,2,8],
    [9,5,4]]

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

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

for r in result:
   print(r)

Output

[10, 4, 6]
[15, 7, 15]
[14, 23, 23]
  • Here we have already made a result matrix in which all the elements are already 0.
  • Now we will start the loop and keep on adding the respective elements and replace 0s in the resultant matrix with the result for that position.

NOTE – Make sure the dimensions of both the matrices are the same.

Check out our other python programming examples

Leave a Reply

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