Search code examples
pythonsympysymbolic-math

Cannot evaluate the trace in sympy


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?


Solution

  • 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