Parse array expressions in sympy

Viewed 49

Does sympy offer a way to work with expressions involving arrays? I'm trying to do something like expr = sympy_parser('x[0]+x[1]') or sympy_parser('sum(x)') and evaluate that via expr.subs({'x': [1,2,3]}).

In the former case, the parser gives an error TypeError: 'Symbol' object is not subscriptable. In the latter case it parses, but subs doesn't evaluate and just returns the expression sum(x) again.

1 Answers

I am not sure if this meets your needs, but you can use sympy Matrix objects:

from sympy import *

x = Matrix([1, 2, 3])
x[0] + x[1]
sum(x)

There is also MatrixSymbol for symbolic computations:

X = MatrixSymbol('x', 3, 1)
(X[0] + X[1]).subs({X: Matrix([1,2,3])})
sum(X).subs({X: Matrix([1,2,3])})
Related