I have a Sympy matrix A and a polynomial expression P, and I would like to compute P(A).
Here is an example:
x = Symbol('x')
P = x**2 - 3*x + 5
A = Matrix([ [1,3], [-1,2] ])
P.subs(x, A)
I expect Sympy to compute A**2 - 3*A + 5*eye(2)
(in the example, the result is the zero matrix).
But this fails with an error message:
AttributeError: ImmutableMatrix has no attribute as_coeff_Mul.
Is there any way to obtain what I want ?
Edit:
I've tried to convert P
into Sympy's polynomial class, and substitute afterwards, but the result is useless:
Poly(P).subs(A)
Poly(Matrix([ [ 1, 3], [-1, 2]])**2 - 3*Matrix([ [ 1, 3],
[-1, 2]]) + 5, Matrix([ [ 1, 3], [-1, 2]]), domain='ZZ')
I can get the correct result with the following function :
def poly_matrix(P, A):
coeffs = Poly(P).all_coeffs()[::-1]
res = zeros(A.rows)
for i in range(len(coeffs)):
res += coeffs[i]*(A**i)
return res
But I'm still looking for a more efficient built-in option.