Python Program to Add two Matrices

0

Python Program to Add two Matrices

  • In this article, we will see how to add two matrices in Python. Before we see how to implement matrix addition in Python.
M1 = [[1,1,1],
      [1,1,1],
      [1,1,1]]

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

Sum of these matrices:
   = [[2,3,4],
      [5,6,7],
      [8,9,10]]

Source Code:

# This program is to add two given matrices

# first matrix
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)

 

Post a Comment

0Comments
Post a Comment (0)