Articles

Program to add two matrix in Python

Program to add two matrix in Python


In this python programming article, we are going to learn to:

  • write a program to add two matrix in python

Program to find sum of two matrices in Python

The program to add two matrix in python is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

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

mat2 = [[11,12,13],
        [14,15,16],
        [17,18,19]]


mat3 = list()
temp = list()

for i in range(3):
    temp=[]
    for j in range(3):
        temp.append(mat1[i][j]+mat2[i][j])
    mat3.append(temp)

for i in mat3:
    print(i)

The output of the program to add two matrix in python is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py                         En
[12, 14, 16]
[18, 20, 22]
[24, 26, 28]

Few important tips about the program

1. A matrix is nothing but a 2D array or a nested list in Python.

2. We iterate upon every row and then every element within that row using indexing to find its sum and store in in a temporary list. Finally, we insert the list into the resultant matrix and again empty the list for the next iteration.

3. Finally, we print the matrix, rowwise.

 

write a program to add two matrix in python:

write a program to add two matrix in python

 


Python Numbers Program
Python Miscellaneous Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Apr 20,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!