15

我正在尝试编写一个添加两个矩阵以通过以下文档测试的函数:

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

然后我写了以下函数:

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

得到了正确的答案。

4

4 回答 4

23

矩阵库

您可以使用numpy支持此功能的模块。

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

本土解决方案:重量级

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

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

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

    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 和关键字参数,您可以在 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]]
于 2011-06-17T07:34:48.657 回答
7
def addM(a, b):
    res = []
    for i in range(len(a)):
        row = []
        for j in range(len(a[0])):
            row.append(a[i][j]+b[i][j])
        res.append(row)
    return res
于 2011-06-17T07:42:39.557 回答
4

另一种解决方案:

map(lambda i: map(lambda x,y: x + y, matr_a[i], matr_b[i]), xrange(len(matr_a)))
于 2011-06-17T07:53:42.400 回答
3
from itertools import izip

def add_matrices(c, d):
    return [[a+b for a, b in izip(row1, row2)] for row1, row2 in izip(c, d)]

但是如上所述,无需重新发明轮子,只需使用numpy,这可能会更快,更灵活。

于 2011-06-17T07:52:02.873 回答