在python中添加两个矩阵 [英] Add two matrices in python

查看:263
本文介绍了在python中添加两个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个将两个矩阵相加以通过以下doctest的函数:

I'm trying to write a function that adds two matrices to pass the following doctests:

  >>> a = [[1, 2], [3, 4]]
  >>> b = [[2, 2], [2, 2]]
  >>> add_matrices(a, b)
  [[3, 4], [5, 6]]
  >>> c = [[8, 2], [3, 4], [5, 7]]
  >>> d = [[3, 2], [9, 2], [10, 12]]
  >>> add_matrices(c, d)
  [[11, 4], [12, 6], [15, 19]]

所以我写了一个函数:

def add(x, y):
    return x + y

然后我编写了以下函数:

And then I wrote the following function:

def add_matrices(c, d):
    for i in range(len(c)):
        print map(add, c[i], d[i])

然后我 sort 得到正确的答案.

And I sort of get the right answer.

推荐答案

矩阵库

您可以使用numpy模块,该模块对此具有支持.

Matrix library

You can use the numpy module, which has support for this.

>>> import numpy as np

>>> a = np.matrix([[1, 2], [3, 4]])
>>> b = np.matrix([[2, 2], [2, 2]])

>>> a+b
matrix([[3, 4],
        [5, 6]])


本地解决方案:重量级

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


Home-grown solution: heavyweight

Assuming you wanted to implement it yourself, you'd set up the following machinery, which would let you define arbitrary pairwise operations:

from pprint import pformat as pf

class 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

现在添加成对方法就像馅饼一样简单:

Now adding pairwise methods is as easy as pie:

    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]]

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

You can even add pairwise exponentiation, negation, binary operations, etc. I do not demonstrate it here, because it's probably best to leave * and ** for matrix multiplication and matrix exponentiation.

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

If you just want a really simple way to map an operation over only two nested-list matrices, you can do this:

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和关键字.

With an additional if-else and keyword argument, you can use indices in your lambda. Below is an example of how to write a matrix row-order enumerate function. The if-else and keyword were omitted above for clarity.

>>> 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函数:

So we could write the above add_matrices function like so:

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

演示:

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

这篇关于在python中添加两个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆