FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

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, lets see what it looks like:.

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]]

Program for adding two matrices

To represent a matrix, we are using the concept of nested lists. All the elements of both the input matrices are represented as nested lists. All the elements of output list are initialized as zero.
We are iterating the matrix and adding the corresponding elements of both the given matrices and assigning the value in the output matrix.

# This program is to add two given matrices
# We are using the concept of nested lists to represent matrix

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

Output

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






Leave Comment