user42298
user42298

Reputation: 1911

Sum of a list of SymPy matrices

My python list contains sympy matrix object, and I need to sum them all. If all list elements are just symbols, then using built-in sum function in python works fine.

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

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

But for the elements of matrix type, sum function looks not working.

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

How can I resolve this problem?

Upvotes: 3

Views: 4825

Answers (2)

user8193156
user8193156

Reputation:

I don't really know how the built-in function sum works, perhaps it kinda looks like this.

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

Now consider the following lines of code.

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

What we can conclude is you add any sympy.core.symbol.Symbol(btw there are more such as Sum and Pow) to integer but not sympy.matrices.dense.MutableDenseMatrix

Upvotes: 0

user6655984
user6655984

Reputation:

This is why Python's sum function has an optional "start" argument: so you can initialize it with a "zero object" of the kind you are adding. In this case, with a zero matrix.

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

Upvotes: 4

Related Questions