栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在python中添加两个矩阵

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

在python中添加两个矩阵

矩阵库

您可以使用

numpy
支持此功能的模块。

>>> import numpy as np>>> a = np.matrix([[1, 2], [3, 4]])>>> b = np.matrix([[2, 2], [2, 2]])>>> a+bmatrix([[3, 4],        [5, 6]])

本土解决方案:重量级

假设您想自己实现它,那么您将设置以下机器,使您可以定义任意成对操作:

from pprint import pformat as pfclass Matrix(object):    def __init__(self, arrayOfRows=None, rows=None, cols=None):        if arrayOfRows: self.data = arrayOfRows        else: self.data = [[0 for c in range(cols)] for r in range(rows)]        self.rows = len(self.data)        self.cols = len(self.data[0])    @property    def shape(self):          # myMatrix.shape -> (4,3)        return (self.rows, self.cols)    def __getitem__(self, i): # lets you do myMatrix[row][col        return self.data[i]    def __str__(self):        # pretty string formatting        return pf(self.data)    @classmethod    def map(cls, func, *matrices):        assert len(set(m.shape for m in matrices))==1, 'Not all matrices same shape'        rows,cols = matrices[0].shape        new = Matrix(rows=rows, cols=cols)        for r in range(rows): for c in range(cols):     new[r][c] = func(*[m[r][c] for m in matrices], r=r, c=c)        return new

现在,添加成对方法非常容易:

    def __add__(self, other):        return Matrix.map(lambda a,b,**kw:a+b, self, other)    def __sub__(self, other):        return Matrix.map(lambda a,b,**kw:a-b, self, other)

例:

>>> a = Matrix([[1, 2], [3, 4]])>>> b = Matrix([[2, 2], [2, 2]])>>> b = Matrix([[0, 0], [0, 0]])>>> print(a+b)[[3, 4], [5, 6]]>>> print(a-b)[[-1, 0], [1, 2]]

您甚至可以添加成对取幂,取反,二进制运算等。在此不做演示,因为最好将*留给矩阵乘法和矩阵求幂。


本土解决方案:轻巧

如果您只想以一种非常简单的方式将操作映射到两个嵌套列表矩阵上,则可以执行以下操作:

def listmatrixMap(f, *matrices):    return         [ [     f(*values)      for c,values in enumerate(zip(*rows)) ]  for r,rows in enumerate(zip(*matrices))        ]

演示:

>>> listmatrixMap(operator.add, a, b, c))[[3, 4], [5, 6]]

通过附加的if-else和keyword参数,您可以在lambda中使用索引。下面是一个如何编写矩阵行顺序

enumerate
函数的示例。为了清楚起见,上面省略了if-else和关键字。

>>> listmatrixMap(lambda val,r,c:((r,c),val), a, indices=True)[[((0, 0), 1), ((0, 1), 2)], [((1, 0), 3), ((1, 1), 4)]]

编辑

所以我们可以这样写上面的

add_matrices
函数:

def add_matrices(a,b):    return listmatrixMap(add, a, b)

演示:

>>> add_matrices(c, d)[[11, 4], [12, 6], [15, 19]]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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