栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实现矩阵计算

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实现矩阵计算

矩阵其实就是二维数组
这里用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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/226114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号