I am trying to make a Mathematica program run faster. Here is part of the original version. It takes as input the integers X (of order 100), J (of order 10000), and n (of order 100), the real number p (of order 1), and the rank 2 list NRR of integers (or order 10000 by 4).
hKer=Table[0,{k,1,X},{j,1,J},{i,1,n}];
For[j=1,j<n+1,j++,
For[i=1,i<n+1,i++,
hKer[[1,j,i]]=KroneckerDelta[j,i]]];
For[k=2,k<X+1,k++,
For[j=1,j<J+1,j++,
For[i=1,i<n+1,i++,
hKer[[k,j,i]]=N[(1-p)hKer[[k-1,j,i]]+(p/Length[NRR[[j]]])Sum[hKer[[k-1,NRR[[j,l]],i]],{l,1,Length[NRR[[j]]]}]]]]];
Searching the internet for advice led me to try compiling this program. Copying an example on stackoverflow, I arrived at the following version.
fhKer=Compile[{{X,_Integer},{J,_Integer},{n,_Integer},{p,_Real},{NRR,_Integer,2}},
Module[{hKer},
hKer=Table[0.,{k,1,X},{j,1,J},{i,1,n}];
Do[hKer[[1,j,i]]=If[j==i,1,0],{j,1,n},{i,1,n}];
Do[hKer[[k,j,i]]=N[(1-p)K[[k-1,j,i]]+(p/Length[NRR[[j]]])Sum[hKer[[k-1,NRR[[j,l]],i]],{l,1,Length[NRR[[j]]]}],{k,2,X},{j,1,J},{i,1,n}];
hKer]]
The compiled program runs more slowly than the original version. I checked that the compiled program does not contain a MainEvaluate, which was put forth as a potential problem on stackexchange. I do not currently have any good ideas either for making the compiled program run more quickly or for modifying the original version to run more quickly. I would greatly appreciate any suggestions.
(p/Length[NRR[[j]])
should be(p/Length[NRR[[j]]])
. Also can you post some example inputsX
,J
,n
,p
andNRR
? $\endgroup$ – dr.blochwave Jul 30 '14 at 10:53Compile
learn to utilize mathematica object oriented programming and wealth of built in functions. For a start look upInentityMatrix
.. $\endgroup$ – george2079 Jul 30 '14 at 12:18IdentityMatrix
... :) @OP: Note thatK
has a special use in Mathematica; evaluate?K
to find out. $\endgroup$ – Michael E2 Jul 30 '14 at 12:33