Python program to add two matrices and print the resulting matrix

Here, we are writing a Python program to add two matrices and print the resulting matrix.
Submitted by Shivang Yadav, on February 22, 2021

Matrix in python is a two-dimensional data structure which is an array of arrays.

Python program to add two matrices

Mat1 = ()
row = int(input("Enter Row : "))
col = int(input("Enter Cols : "))
print("Matrix 1 : ")
for i in range(row):
    c=()
    for j in range(col):
      v=int(input("Enter Value {},{}:".format(i,j)))
      c+=(v,)
    Mat1 += (c,)

Mat2 = ()
print("Matrix 2 : ")
for i in range(row):
    c = ()
    for j in range(col):
        v = int(input("Enter Value {},{}:".format(i, j)))
        c += (v,)
    Mat2 += (c,)

print("Value of matrix 1 : ", end = " ")
print(Mat1)
print("Value of matrix 2 : ", end = " ")
print(Mat2)

sumMat = ()
print("Sum Matrix : ", end = " ")
for i in range(row):
    c=()
    for j in range(col):
        v = Mat1[i][j]+Mat2[i][j]
        c+=(v,)
    sumMat+=(c,)

print(sumMat)

Output:

Enter Row : 3 2
Enter Cols : 2
Matrix 1 : 
Enter Value 0,0:43
Enter Value 0,1:23
Enter Value 1,0:65
Enter Value 1,1:7
Matrix 2 : 
Enter Value 0,0:2
Enter Value 0,1:5
Enter Value 1,0:7
Enter Value 1,1:4
Value of matrix 1 :  ((43, 23), (65, 7))
Value of matrix 2 :  ((2, 5), (7, 4))
Sum Matrix :  ((45, 28), (72, 11))

In the above code, we have created two mat1 and mat2. Then we have feeded both of them using the input from the user. Then added the values of these matrices and stored it into a sum matrix and the print all the matrices.

Python Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.