Cannot evaluate the trace in sympy

Question:

I’m trying to get a symbolic expression for the trace of a matrix in sympy, like this:

from sympy import * 
A, B = symbols('A B')
M = Matrix([[A, 0], [0, B]])
t = Trace(M)
print(t)

And the output is as follows:

Trace(Matrix([
[A, 0],
[0, B]]))

Whereas I want an output like A + B. I have tried using the evalf() function but I get the same output. How do I make the Trace() function evaluate the trace?

Asked By: SO INS

||

Answers:

Trace represents an unevaluated trace. You can evaluate it with:

t.doit()
# out: A + B

or you can use the trace() method of a matrix to directly compute it:

M.trace()
# out: A + B
Answered By: Davide_sd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.