How to add two matrices using operator overloading in Python

1 Answer

0 votes
class Matrix:
    def __init__(self, List):
        self.List = List
    def print(self):
        print(self.List)
    def __add__(self, m):
        result = Matrix([])
        for i in range(len(self.List)):
            for j in range(len(self.List[0])):
                result.List.append(self.List[i][j] + m.List[i][j])
        return result
        
m1 = Matrix([[1,2],[3,4]])
m2 = Matrix([[4,5],[6,7]])

m12 = m1 + m2

m12.print()




'''
run:

[5, 7, 9, 11]

'''

 



answered Oct 6, 2021 by avibootz

Related questions

3 answers 231 views
231 views asked May 31, 2017 by avibootz
1 answer 144 views
144 views asked Dec 2, 2022 by avibootz
1 answer 223 views
1 answer 249 views
1 answer 217 views
2 answers 273 views
...