ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.