Python Program to Add Two Matrices


Example

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Program to add two matrices using nested loop

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

Y = [[4,8,1],
    [6,8,3],
    [4,6,9]]

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

[5, 15, 4]
[10, 13, 9]
[6, 14, 18]


Explanation

In this program we have used nested for loops to iterate through each row and each column. At each point we add the corresponding elements in the two matrices and store it in the result.