Here is another method to compute the trace of a matrix power. As already mentioned, the trace of a matrix power is equal to the power sum of the matrix's eigenvalues. The first key is to recognize that these power sums can be computed through a linear recurrence relation, where the required coefficients are the coefficients of the matrix's eigenpolynomial. The second key is that the initial conditions for this linear recurrence can be derived from the coefficients as well, by combining the Vieta and Newton-Girard formulae.
To be able to use the Newton-Girard formulae, I'll give an auxiliary routine for generating the required coefficient matrix from the polynomial coefficients:
ngMatrix[p_?VectorQ] := Module[{n = Length[p]},
SparseArray[{Band[{1, 1}] -> 1, {j_, k_} /; j > k :> p[[j - k]]}, {n, n}]]
I'll use a numerical example first for this demo:
n = 4;
mat = Array[Min, {n, n}]
{{1, 1, 1, 1}, {1, 2, 2, 2}, {1, 2, 3, 3}, {1, 2, 3, 4}}
rec =
(-1)^(n - 1) Reverse[Most[CoefficientList[CharacteristicPolynomial[mat, x], x]]]
{10, -15, 7, -1}
init = LinearSolve[ngMatrix[-rec], Range[n] rec]
{10, 70, 571, 4726}
With[{m = 50}, First[LinearRecurrence[rec, init, {m}]]] // AbsoluteTiming
{0.000694122, 8510938110502117856062697655362747468175263710}
Tr[MatrixPower[mat, 50]] // AbsoluteTiming
{0.00263071, 8510938110502117856062697655362747468175263710}
For the OP's symbolic example:
n = 6; SetAttributes[s, Orderless]; S = Array[s, {n, n}];
rec = Simplify[(-1)^(n - 1)
Reverse[Most[CoefficientList[CharacteristicPolynomial[S, x], x]]]];
init = Simplify[LinearSolve[ngMatrix[-rec], Range[n] rec]];
and then evaluate
First[LinearRecurrence[rec, init, {12}]]
However, I've found the timings to be a bit inconsistent; sometimes MatrixPower[]
is faster, and sometimes LinearRecurrence[]
is faster (not counting the time needed to set up rec
and init
).
MatrixPower
. $\endgroup$tr
, I am going to integrate it with respect to its matrix elements, $s_{ij}$ (the integration step is very fast -- I have already made it as efficient as possible; the bottleneck is the trace). $\endgroup$