繁体   English   中英

SymPy矩阵列表的总和

[英]Sum of a list of SymPy matrices

我的python列表包含sympy矩阵对象,我需要将它们全部加起来。 如果所有列表元素都只是符号,则在python中使用内置的sum函数可以正常工作。

import sympy as sp
x = sp.symbols('x')
ls = [x, x+1, x**2]
print(sum(ls))

>>> x**2 + 2*x + 1

但是对于矩阵类型的元素,求和函数似乎不起作用。

import sympy as sp
ls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3]
print(sum(ls))

>>> TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>

我该如何解决这个问题?

这就是为什么Python的sum函数具有一个可选的“ start”参数的原因:因此,您可以使用要添加的那种“零对象”对其进行初始化。 在这种情况下,矩阵为零。

>>> print(sum(ls, sp.zeros(2)))
Matrix([[9, 0], [0, 9]])

我真的不知道内置函数sum工作原理,也许有点像这样。

def _sum(data):
    total = 0
    for i in data:
        total += i
    return total

现在考虑以下代码行。

>>> import sympy
>>> x = sympy.symbols('x')
>>> x
x
>>> print(0+x)
x
>>> x = sympy.symbols('x')
>>> matrix=sympy.eye(3)
>>> matrix
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> print(0+x)
x
>>> print(0+matrix)
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    print(0+matrix)
  File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary_op_wrapper
    return func(self, other)
  File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 2061, in __radd__
    return self + other
  File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary_op_wrapper
    return func(self, other)
  File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 1964, in __add__
    raise TypeError('cannot add %s and %s' % (type(self), type(other)))
TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>
>>> 

我们可以得出的结论是,您将任何sympy.core.symbol.Symbol (顺便说一句,例如Sum和Pow)添加到整数,但不添加sympy.matrices.dense.MutableDenseMatrix

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM