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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

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