Python program to add two matrices using '+' operator overloading | Matrix Addition in Python | Matrix Addition using Class


Write a Python program to add two matrices using '+' operator overloading.
Source Code:
class A:
    def __init__(self, x):
        self.x = list(x)

    def disp(self):
        for i in range(len(self.x)):
            print(self.x[i])
    
    def __add__(self, other):
        for i in range(len(self.x)):
            for j in range(len(self.x[0])):
            self.x[i][j] = self.x[i][j] + other.x[i][j]
        return self.x

m1 = A([[3,2,7],
   [2,3,5],
   [4,2,6],
   [2,4,6]])

m2 = A([[3,6,1],
   [4,2,6],
   [7,2,5],
   [5,9,3]])

print("First Matrix is:")
m1.disp()
print("\n\nSecond Matrix is:")
m2.disp()

m3 = m1 + m2

print("\n\nAddition of the two Matrices is:")
for i in range(len(m3)):
    print(m3[i])

OUTPUT:
First Matrix is:
[3, 2, 7]
[2, 3, 5]
[4, 2, 6]
[2, 4, 6]


Second Matrix is:
[3, 6, 1]
[4, 2, 6]
[7, 2, 5]
[5, 9, 3]


Addition of the two Matrices is:
[6, 8, 8]
[6, 5, 11]
[11, 4, 11]
[7, 13, 9]


For any query, please comment below.
SUBSCRIBE

Post a Comment

2 Comments