,

Python Program to Add two Matrices


Python Program to Add two Matrices


M1 = [[1, 1, 1],
      [1, 1, 1],
      [1, 1, 1]]

# second matrix
M2 = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]]

# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(M1)):
    for j in range(len(M1[0])):
        sum[i][j] = M1[i][j] + M2[i][j]

# displaying the output matrix
for num in sum:
    print(num)


Output:

 [2, 3, 4]
 [5, 6, 7]
 [8, 9, 10]