user3780691
user3780691

Reputation: 83

Evaluating a function in SymPy with a matrix as input

I want to make a polynomial in SymPy, but ideally I want to write my code as general as possible:

from sympy import *

sx, sa0, sa1, sa2 = symbols('x sa0 sa1 sa2')

sa = MatrixSymbol('a',3,1)

polynomial = sum([sa[i,0]*sx**i/factorial(i) for i in range(sa.shape[0])])

The following expression gives the polynomial explicitly but the code is not as general as I would like it to be:

poly2 = sx**2*sa2/2 + sx*sa1 + sa0

In this expression sa0, sa1, sa2 replace sa[0,0], sa[1,0], and sa[2,0], respectively.

My problem is that I can evaluate poly2 but not 'polynomial':

>>> print(poly2.evalf(subs={sx: 10, sa0: 1, sa1: 1, sa2: 1}))
>>> 61.0000000000000
>>> print(polynomial.evalf(subs={sx: 10, sa[0,0]: 1, sa[1,0]: 1, sa[2,0]: 1}))
>>> 0.5*x**2*a[2, 0] + x*a[1, 0] + a[0, 0]
>>> print(polynomial.evalf(subs={sx: 10, sa: [[1, 1, 1]]}))
>>> 0.5*x**2*a[2, 0] + x*a[1, 0] + a[0, 0]

How can I insert values of the MatrixSymbol object sa in the function?

Upvotes: 0

Views: 348

Answers (1)

asmeurer
asmeurer

Reputation: 91450

Try using xreplace instead of evalf. Ideally subs would also work, but it looks like there is a bug.

Upvotes: 0

Related Questions