0

I have a Do function which gives me a column of expressions. How can I get the Do function to give me these expressions in a list.

i.e The do function gives me this: a b c d

I would like it do give me this: {a,b,c,d}

Hollie
  • 1

2 Answers2

1

While belisarius is right that you can usually make the list you want directly with Table, I'm often in a situation where I need to build up a list with a Do loop. Say I'm numerically propagating a wave function through a series of discrete time steps and need to collect the expectation values for several operators at each time point, this is how I do it.

(*Initialize the list outside the loop*)
list1 = {};
list2 = {};
Do[
 (*code here*)
 AppendTo[list1,value1];
 AppendTo[list2,value2];
 ,{n,ninit,nfin,nstep}];
Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • 1
    have a look at Reap/Sow – george2079 Oct 20 '14 at 16:13
  • AppendTo will lead to $O(n^2)$ complexity. Reap/Sow will be much faster when collecting lots of results. – Szabolcs Oct 20 '14 at 19:13
  • I can change it to use Reap/Sow but don't really see much improvement. When I run something like what I have written above, the part inside (code here) takes orders of magnitude longer to run than the AppendTo statements. Also I don't see how to use Reap to generate multiple lists, aside from doing something like biglist=Reap[Do[(*code here*)Sow[{value1,value2}];,{n,ninit,nfin,nstep}]][[2,1]]; and then after the loop is done, doing {list1,list2}=Transpose[biglist];. So in my code this will only shave off at most 1% of the execution time, but I suppose every bit helps. – Jason B. Oct 21 '14 at 08:04
0

So normally I would consider a "column" of expressions to be of the form:

col0={{"a"}, {"b"}, {"c"}, {"d"}}

Note that Mathematica uses Row Major order.

row0=First[Transpose[col0]]

would extract the first column into a row list.

As previously mentioned, appending to lists with AppendTo in a do loop can be expensive. Avoid if possible. Consider using Table instead.

col1=Table[FromCharacterCode[{{iChr}}], {iChr, 97, 100, 1}]
row1=Table[FromCharacterCode@iChr, {iChr, 97, 100, 1}]

If the code in your Do loop is lengthy, you can address this by putting it into a module, and then calling that module from the Table command. (i.e. Replace FromCharacterCode in the toy example with a function call to your module.)

rivercfd
  • 136
  • 4