继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Python实现矩阵计算

Vimo
关注TA
已关注
手记 3
粉丝 33
获赞 104

矩阵其实就是二维数组
这里用Python模拟一下矩阵运算的加法和乘法(Python3实现)


import copy
from functools import reduce

class Matrix(object):

    def __init__(self, dyadic_array):
        self.matrix = dyadic_array

    def __str__(self):
        s = ''
        for arr1 in self.matrix:
            l = len(arr1)
            for index2, item in enumerate(arr1):
                if index2 == 0:
                    s += '▎\t'
                s += str(item) + '\t'
                if index2 + 1 == l:
                    s += '▎\n'
        return s

    def __add__(self, matrix):
        if self.size() != matrix.size():
            print('Size different error')
        clone_matrix = copy.deepcopy(self.matrix)
        for index1, arr1 in enumerate(clone_matrix):
            for index2, item in enumerate(arr1):
                clone_matrix[index1][index2] += matrix.matrix[index1][index2]
        return Matrix(clone_matrix)

    def __mul__(self, matrix):
        m = self.rows()
        n = matrix.cols()
        k = self.cols()
        if k != matrix.rows():
            print('Size error')
        temp_matrix = [([0] * n) for i in range(m)]
        for index1, arr1 in enumerate(temp_matrix):
            row = self.get_row(index1)
            for index2, item in enumerate(arr1):
                col = matrix.get_col(index2)
                temp_matrix[index1][index2] = reduce(lambda x, y=0: x + y, map(lambda i: row[i] * col[i], range(k)))
        return Matrix(temp_matrix)

    def size(self):
        return '%s*%s' % (len(self.matrix), len(self.matrix[0]))

    def rows(self):
        return len(self.matrix)

    def cols(self):
        return len(self.matrix[0])

    def get_row(self, index):
        return self.matrix[index]

    def get_col(self, index):
        return list(map(lambda a: a[index], self.matrix))

a1 = [[4, 0, 3], [4, 6, 7]]
a2 = [[1, 3, 3], [24, 6, 7]]
a3 = [[1, 2], [1, 2], [1, 2]]

m1 = Matrix(a1)
m2 = Matrix(a2)
m3 = Matrix(a3)

m5 = m1 * m3

print(m5)
打开App,阅读手记
11人推荐
发表评论
随时随地看视频慕课网APP