Condensing variables of a matrix

I'm working with matrices such as

M = matrix([
[a, b, 0],
[c, 0, d],
[0, e, 0]])


where a, b, c, d, and e are variables. Then I loop through some numbers for each of a, b, c, d, and e, looking at the eigenvalues of the resulting matrix. $$char(M) = x^3 - ax^2 - (bc + de)x + ade$$ So, I'm doing more work than necessary, and ideally, I'd reduce M down to

 M = matrix([
[a, b, 0],
[1, 0, d],
[0, 1, 0]])


Is there a simple way of using Sage to do so?

edit retag close merge delete

Sort by » oldest newest most voted

You can define a function my_matrix, which transforms Python variables to your matrix:

sage: my_matrix = lambda a,b,c,d,e : matrix([[a, b, 0], [c, 0, d], [0, e, 0]])

sage: my_matrix(pi,0,1,1/2,42)
[ pi   0   0]
[  1   0 1/2]
[  0  42   0]


Then you can do something like

sage: var('a,b,c,d,e')  # those letters are symbols (like undeterminates), not Python variables.
(a, b, c, d, e)

sage: my_matrix(a,b,1,d,1)
[a b 0]
[1 0 d]
[0 1 0]

sage: my_matrix(a,b,1,d,1).charpoly()
x^3 - a*x^2 + (-b - d)*x + a*d

sage: my_matrix(a,a,a,a,a)
[a a 0]
[a 0 a]
[0 a 0]

more

Maybe I should have been a little more explicit. I want a method for determining when a matrix can have the number of variables reduced. Implementing the reduction is the easy part.