5
$\begingroup$

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.

$\endgroup$
1
7
$\begingroup$

When size is not known, I like to use Sow and Reap and use Do instead of Table

ClearAll[sum, cumsum];
sum = 0;
cumsum = First@Last@Reap@Do[sum = sum + i; Sow@sum, {i, 10}]

Mathematica graphics

This should be more efficient than AppendTo


ClearAll[sum, cumsum];
sum = 0;
Timing[First@Last@Reap@Do[sum = sum + i; Sow@sum, {i, 100000}]][[1]]
(*0.078 seconds*)


ClearAll[sum, cumsum];
cumsum = {}; sum = 0;
Timing[Table[sum = sum + ii; AppendTo[cumsum, sum], {ii, 100000}]][[1]]
(* 12.2344 *)
$\endgroup$
2
  • 1
    $\begingroup$ Indeed, Sow+Reap was made for this, and is way better than Append(To). +1 $\endgroup$ May 4 '20 at 7:03
  • 1
    $\begingroup$ First@Last@Reap@Do[Sow[sum += i], {i, 100000}] a little faster. $\endgroup$
    – kglr
    May 7 '20 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.