首页 > 编程知识 正文

python实现矩阵乘法,矩阵加法和乘法

时间:2023-05-05 06:18:34 阅读:264827 作者:2758

矩阵加法需要矩阵同型
矩阵乘法A·B需要满足A的列等于B的行
代码如下

class MatrixCalc: A = [] B = [] def __init__(self, shapeA, shapeB): self.shapeA = shapeA self.shapeB = shapeB def input_(self): print("Please input the Matrix A and the Matrix B below:") MatrixCalc.A = [] MatrixCalc.B = [] for i in range(self.shapeA[0]): MatrixCalc.A.append([int(e) for e in input().split()]) print("") for i in range(self.shapeA[1]): MatrixCalc.B.append([int(e) for e in input().split()]) def add(self): if self.shapeA[0] != self.shapeB[0] or self.shapeA[1] != self.shapeB[1]: print("Error!") else: MatrixCalc.input_(self) print("The result is:") for i in range(self.shapeA[0]): print([MatrixCalc.A[i][j] + MatrixCalc.B[i][j] for j in range(self.shapeA[1])]) def multiply(self): if self.shapeA[1] != self.shapeB[0]: print("Error!") else: MatrixCalc.input_(self) print("The result is:") C = [] for i in range(self.shapeA[0]): tmp = [] for k in range(self.shapeB[1]): sum = 0 for j in range(self.shapeA[1]): sum += MatrixCalc.A[i][j] * MatrixCalc.B[j][k] tmp.append(sum) C.append(tmp) for i in C: for j in i: print(j, end=' ') print()if __name__ == '__main__': shapeA = [int(i) for i in input("Please input the shape of Matrix A:").split()] shapeB = [int(i) for i in input("Please input the shape of Matrix B:").split()] cal_mode = input("How do you want to calculate it? Choose one:n[1] '+'n[2] '*'n") M = MatrixCalc(shapeA, shapeB) if cal_mode is '+': M.add() else: M.multiply()

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。