I got a problem and have to rewrite the following code and try to make it fast. Does someone have any idea how to solve it?
Total@Flatten@MatrixPower[Partition[270^5*Range[270^2],270],12]
There seems to be a pattern between the size of input matrix (m
) and the sum of elements in MatrixPower[m, 12]
that can be discovered cheaply using FindSequenceFunction
on a short list of small sizes:
(list = With[{mm = ArrayReshape[Range[#^2], {#, #}]},
Total[MatrixPower[mm, 12], 2]] & /@ Range[40];) // RepeatedTiming // First
0.11
ClearAll[seqF]
(seqF[k_] := Evaluate @ FindSequenceFunction[list, k])//RepeatedTiming // First
0.0040
seqF[k]
seqF[270]
evaluates almost instantly:
(270^5)^12 seqF[270] // RepeatedTiming
Compare with
Total @ Flatten @ MatrixPower[Partition[270^5*Range[270^2], 270], 12] //
RepeatedTiming
Total@Flatten@MatrixPower[N@Partition[270^5*Range[270^2], 270], 12]
(notice theN@
) evaluates instantly. $\endgroup$N
, I was able to cut the time to about 60% on my machine by factoring out the270^5
:((270^5)^12)*Total@Flatten@MatrixPower[Partition[Range[270^2],270],12]
$\endgroup$270
to something else? I'm wondering if it would help to find a way to compute it just once in the context of whatever code is enclosing it, but the feasibility of this depends on which parameters need to vary each time your code computes it. $\endgroup$