TransWikia.com

Rewrite code to make it faster

Mathematica Asked by Hans Peter on August 8, 2021

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]

One Answer

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

Answered by kglr on August 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP