@classmethod defzero(cls, r, c): '''返回一个r行c列的零矩阵''' return cls([[0]*c for _ inrange(r)])
def__add__(self, another): '''返回两个矩阵的加法结果''' assertself.shape() == another.shape(),\ "Error in adding. Shape of matrix must be same" return Matrix([[a+b for a,b inzip(self.row_vector(i), another.row_vector(i))] for i inrange(self.row_num())])
def__sub__(self, another): '''返回两个矩阵的减法结果''' assertself.shape() == another.shape(),\ "Error in subtracting. Shape of matrix must be same" return Matrix([[a-b for a,b inzip(self.row_vector(i), another.row_vector(i))] for i inrange(self.row_num())])
def__mul__(self, k): '''返回矩阵的数量乘结果: self * k''' return Matrix([[e*k for e inself.row_vector(i)] for i inrange(self.row_num())])
defdot(self, another): '''返回矩阵乘法的结果''' ifisinstance(another, Vector): assertself.col_num() == len(another),\ "Error in Matrix-Vector Mul" return Vector([self.row_vector(i).dot(another) for i inrange(self.row_num())])
ifisinstance(another, Matrix): assertself.col_num() == another.row_num(),\ "Error in Matrix-Matrix Mul" return Matrix([[self.row_vector(i).dot(another.col_vector(j)) for j inrange(another.col_num())] for i inrange(self.row_num())])
classMatrix: def__init__(self, list2d): self._values = [row[:] for row in list2d] @classmethod defzero(cls, r, c): '''返回一个r行c列的零矩阵''' return cls([[0]*c for _ inrange(r)])
defT(self): '''返回矩阵的转置矩阵''' return Matrix([[e for e inself.col_vector(i)] for i inrange(self.col_num())]) def__add__(self, another): '''返回两个矩阵的加法结果''' assertself.shape() == another.shape(),\ "Error in adding. Shape of matrix must be same" return Matrix([[a+b for a,b inzip(self.row_vector(i), another.row_vector(i))] for i inrange(self.row_num())])
def__sub__(self, another): '''返回两个矩阵的减法结果''' assertself.shape() == another.shape(),\ "Error in subtracting. Shape of matrix must be same" return Matrix([[a-b for a,b inzip(self.row_vector(i), another.row_vector(i))] for i inrange(self.row_num())]) defdot(self, another): '''返回矩阵乘法的结果''' ifisinstance(another, Vector): assertself.col_num() == len(another),\ "Error in Matrix-Vector Mul" return Vector([self.row_vector(i).dot(another) for i inrange(self.row_num())]) ifisinstance(another, Matrix): assertself.col_num() == another.row_num(),\ "Error in Matrix-Matrix Mul" return Matrix([[self.row_vector(i).dot(another.col_vector(j)) for j inrange(another.col_num())] for i inrange(self.row_num())])
def__mul__(self, k): '''返回矩阵的数量乘结果: self * k''' return Matrix([[e*k for e inself.row_vector(i)] for i inrange(self.row_num())])