I wrote the following code to do basic matrix operations. It works for me, but I'm not sure it's the best way to do it.
Do you have recommendation?
Is it the right way when I use return Matrix(...)?
Code: Select all
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
class Matrix(object):
def __init__(self, mat):
self.mat = mat
def __repr__(self):
return self.mat
def __add__(self, b):
return Matrix([list(map(add, *ab)) for ab in zip(self.mat, b.mat)])
def __sub__(self, b):
return Matrix([list(map(sub, *ab)) for ab in zip(self.mat, b.mat)])
def __matmul__(self, b):
return Matrix([[sum(map(mul, _a, _b)) for _b in zip(*b.mat)] for _a in self.mat])
Code: Select all
>>> a = Matrix([[1, 2, 3], [4, 5, 6]])
>>> b = Matrix([[10, 11], [20, 21], [30, 31]])
>>> c = Matrix([[-23, 3, 8], [-13, 17, -21]])
>>> d = Matrix([[32, 17], [-3, 11]])
>>> a @ b
[[140, 146], [320, 335]]
>>> a + c
[[-22, 5, 11], [-9, 22, -15]]
>>> a - c
[[24, -1, -5], [17, -12, 27]]
>>> a @ b + d
[[172, 163], [317, 346]]