用python实现矩阵乘法

题目:只用python的类和列表,实现矩阵乘法。

分析:先给定用户输入,再实现乘法。若有矩阵a和b,axb的规则是a的每一行乘b的每一列,每一次都要求和。

class Matmul(object):
    # mat_shape = (row, col) 元组,矩阵大小
    def __init__(self, mat_shape):
        self.cube = []
        self.row = mat_shape[0]
        self.col = mat_shape[1]

    def add_value(self):
        tmp = []
        for _ in range(self.row):
            for _ in range(self.col):
                tmp.append(int(input('按行输入矩阵: ')))

            self.cube.append(tmp)
            tmp = []

    def show(self):
        print("the cube is :", self.cube)

    def multiply(self, other):
        if self.col != other.row:
            print("Not have the permission!")
        else:
            tmp_result = []
            cub_result = []
            tmp = []
            for a in range(self.row):
                for b in range(self.col):
                    for x in range(other.row):
                        tmp_result.append(self.cube[a][x] * other.cube[x][b])
                    tmp.append(sum(tmp_result))
                    tmp_result = []
                cub_result.append(tmp)
                tmp = []
            print(cub_result)



这就实现了矩阵乘法,测试一下。

mat1 = Matmul(mat_shape=(2, 3))
mat2 = Matmul(mat_shape=(3, 3))
print('矩阵1;')
mat1.add_value()
print('矩阵2:')
mat2.add_value()
mat1.show()
mat2.show()
print('结果为:')
mat1.multiply(mat2)

结果如下:

正确。

猜你喜欢

转载自blog.csdn.net/HollyRan/article/details/87372799