Code to calculate characteristic polynomial?

I’m referring to

det(\lambda I - A)

I’m not finding a function to calculate this (it’s charpoly in Matlab).

Happy to write my own, just want to make sure i’m not duplicating effort.

Thanks

p.s. well actually i’m probably not “happy” to write my own, i sure it’s non-trivial…

Why do you need this? For numerical calculations, the coefficients of the characteristic polynomial are generally useless (because even a tiny error in the coefficients radically changes the roots).

1 Like

for Cayley Hamilton. i wanted to play with it as a method for matrix multiplication. Not as a serious method to calculate it, just for educational purposes.

Looks like this works.

julia> using LinearAlgebra

julia> using Polynomials

julia> a=[[1,3] [2,4]]
2×2 Array{Int64,2}:
 1  2
 3  4
julia> poly(eigvals(a))
Poly(-1.9999999999999998 - 5.0*x + 1.0*x^2)

That was easy.

2 Likes

Here is code that gives a more symbolic computation of the characteristic polynomial (with integer coefficients as you’d want for this matrix):

using AbstractAlgebra
R, x = ZZ["x"] # make "x" like a symbolic variable
A = [1 2; 3 4] # normal Julia matrix
M = matrix(R, A) # special matrix object
B = x*one(M) - M # think B = x*I - A
det(B) # x^2 - 5*x - 2 : characteristic polynomial of A
3 Likes

One can actually get the characteristic polynomial directly without building the matrix over the polynomial ring (this is also more efficient):

julia> using AbstractAlgebra

julia> A = [1 2; 3 4];

julia> B = matrix(ZZ, A);

julia> Zx, x = ZZ["x"];

julia> f = charpoly(Zx, B)
x^2 - 5*x - 2

julia> f(B)
[0  0]
[0  0]
4 Likes

Cool! Seems like something like this 1-line addition to the package would be useful?

AbstractAlgebra.charpoly(A::Matrix) = charpoly(ZZ["x"][1], matrix(ZZ,A))

Then charpoly(A) would work “as expected” out of the box :slight_smile:
(I realize that one might want a different letter than x…)

2 Likes