I have a class named Matrix, this class inherits from Python's list. The class currently can perform matrix multiplication, adding rows using list.extend, add a row using list.append, and also transpose.
The emphasis is on using only built-in tools.
- I would like to know if this code can be made more efficient and readable.
- Also, if there are alternative techniques to produce the same result.
- a supplementary problem (more appropriate in StackOverflow) : I cannot use
copy.deepcopy(A)withAaMatrixobject. That's why i useres = Matrix(...)in themultiplicationfunction.
Thanks.
Here is the code, break into three parts.
Global functions :
# Author: Arief Anbiya
# 11 February, 2018
def dot_product(u, v):
return sum([i*j for i,j in zip(u,v)]
def multiplication(M,N):
assert type(M)==Matrix or type(N)==Matrix
res = None;
if type(M)==type(N)==Matrix and M.ncol()==N.nrow():
res = Matrix([[0 for i in range(N.ncol())] for j in range(M.nrow())]);
for i in range(M.nrow()):
for j in range(N.ncol()):
res[i][j] = dot_product(M[i], [N[k][j] for k in range(N.nrow())]);
elif (type(M)==int or type(M)==float):
res = Matrix([[N[j][i] for i in range(N.ncol())] for j in range(N.nrow())]);
for i in range(res.nrow()):
for j in range(res.ncol()):
res[i][j] *= M;
elif (type(N)==int or type(N)==float):
res = Matrix([[M[j][i] for i in range(M.ncol())] for j in range(M.nrow())]);
for i in range(res.nrow()):
for j in range(res.ncol()):
res[i][j] *= N;
else:
raise TypeError("M and N should be either a compatible Matrix object, or a constant");
return res
Class :
# Author: Arief Anbiya
# 11 February 2018
class Matrix(list):
def __init__(self, the_list):
super().__init__(the_list);
def nrow(self):
m = len(self);
return m
def ncol(self):
n = len(self[0]);
return n
def get_dim(self):
return (self.nrow(),self.ncol())
def __add__(self, M):
res = Matrix(self);
for row in range(self.nrow()):
dumrow = [self[row][col] + M[row][col] for col in range(self.ncol())];
res[row]=dumrow;
return res
def __mul__(self, M):
return multiplication(self, M);
def __rmul__(self,M):
return multiplication(M, self);
def add_rows(self, rows):
super().extend(rows);
def append(self, row):
try:
sum(row); # Check if all numbers
if len(row)<self.ncol():
row.extend([0 for i in range(self.ncol()-len(row))]);
elif len(row)>self.ncol():
[row.pop() for i in range(len(row)-self.ncol())];
super().append(row);
except:
raise AssertionError('Elements in row must be mumbers');
def transpose(self):
return Matrix([[row[i] for row in self] for i in range(self.ncol())]);
def show(self):
print("Printing matrix: ");
for i in self:
print(i);
Test for outputs :
A=Matrix([[1,2,3], [2,3,3]]);
A.show();
B = A+A;
B.show();
B.append([1,11,12])
B.show();
C = 3*B;
C.show();
D = A*B;
D.show()