6
$\begingroup$

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]
$\endgroup$
3
  • 1
    $\begingroup$ Can you use machine-precision results? If you can, Total@Flatten@MatrixPower[N@Partition[270^5*Range[270^2], 270], 12] (notice the N@) evaluates instantly. $\endgroup$
    – MarcoB
    Mar 10, 2021 at 21:26
  • 2
    $\begingroup$ I think there are still a lot of speedups available, but for one, if you can't use N, I was able to cut the time to about 60% on my machine by factoring out the 270^5: ((270^5)^12)*Total@Flatten@MatrixPower[Partition[Range[270^2],270],12] $\endgroup$
    – thorimur
    Mar 10, 2021 at 21:44
  • $\begingroup$ Do you need to do this computation multiple times? And do you need to vary parameters each time, e.g. change 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$
    – thorimur
    Mar 10, 2021 at 21:46

1 Answer 1

8
$\begingroup$

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]

enter image description here

seqF[270] evaluates almost instantly:

(270^5)^12 seqF[270] // RepeatedTiming

enter image description here

Compare with

Total @ Flatten @ MatrixPower[Partition[270^5*Range[270^2], 270], 12] // 
 RepeatedTiming

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.