I often would have a calculation, where Table serves the purpose of an effective for loop and I would like to collect some computation in a final list as the Table values are iterated.
As a simple example (Please note that this is not the computation I necessary want to do it is just a representative situation) suppose I want to compute the sum of 10 numbers but save the intermittent calculations in another list, like so:
sum = 0; cumsum = ConstantArray[0, 10];
Table[sum = sum + ii; cumsum[[ii]] = sum;, {ii, 10}];
cumsum
The collection in cumsum requires me to create a constant array. It also requires me to know the size of the array before running the calculation. This code obviously does what I want to do here, but is there a BETTER more Mathematica way of collecting intermittent results in a Table, by saving them in an array that is defined on the spot?
I understand there are possible solutions with
cumsum={}; sum=0;
Table[sum = sum + ii; AppendTo[cumsum,sum];, {ii, 10}];
cumsum
but I am not sure if either of them is the correct way to do it. I apologize if this is a common question, and I appreciate any answers.
Sow
within the Table and enclose the Table expression withReap
? See e.g. Collecting expressions during evaluation. $\endgroup$