0
$\begingroup$

Is it generally better/faster to use the Table function over using Do[Append []]?

For example, I have this piece of code:

inttstar[1] = (tstar[2] - tstar[0])/8; 
inttstar[j_] := 
 inttstar[j] = (1/4)*(tstar[j + 1]/(j + 1) - 
      tstar[Abs[j - 1]]/(j - 1)) - 
        ((-1)^j*tstar[0])/(2*(j^2 - 1))
G = Table[
   Coefficient[inttstar[i], tstar[j], 1], {i, 0, m - 1}, {j, 0, 
    m - 1}];

Gt=Transpose[G];
cmat = T {{0, 1}, {-a, -d}};
cmatk = Outer[Times, cmat, Gt];

aI = {};
Do[
 Do[
  Do[aI = Append[aI, cmatk[[i, k, j]]], {k, 1, 2 n}], {j, 1, 
       m}], {i, 1, 2 n}]

As is, it runs correctly. But, can I improve performance by replacing the Do[Do[Do[....]]] section with a Table function? If so, how would I do that?

$\endgroup$
  • $\begingroup$ Yes, it's recommended because the code looks better if nothing else. You simply write Table[expression,{i,...},{j,...},{k,...}]. $\endgroup$ – C. E. Feb 13 '14 at 22:34
  • $\begingroup$ Related: Alternatives to procedural loops and iterating over lists in Mathematica; also see (13100), (16825), (29349), (39777) $\endgroup$ – Mr.Wizard Feb 13 '14 at 22:37
  • $\begingroup$ @MrW I just wrote a lengthy beginner friendly explanation of why AppendTo is going to be slow ... the question got closed a few seconds before I could hit the post button :-( $\endgroup$ – Szabolcs Feb 13 '14 at 22:38
  • $\begingroup$ @Szabolcs Do you have a copy of it? :-O $\endgroup$ – Mr.Wizard Feb 13 '14 at 22:39
  • $\begingroup$ Anyway, I agree that it's a duplicate, @gKirkland here's the text of what I wrote: pastebin.com/VRbem8Uy $\endgroup$ – Szabolcs Feb 13 '14 at 22:40