在Python中加两个矩阵

15 投票
4 回答
49389 浏览
提问于 2025-04-16 19:45

我正在尝试写一个函数,用来把两个矩阵相加,以通过下面的测试:

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

还有一种解决方案:

map(lambda i: map(lambda x,y: x + y, matr_a[i], matr_b[i]), xrange(len(matr_a)))
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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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

撰写回答