# Use Accumulate while creating Table

Can I somehow create a list and its cumulative sum at the same time, e.g. with Table: Now I do it in two steps

marsYr = 686.9726;
marsYrInt = 687;
startId = {520, 585};
mYrLen = Table[
If[(Floor[(marsYrInt - marsYr)*(i)] -
Floor[(marsYrInt - marsYr)*(i - 1)] == 1) ∧ (i > 0),
marsYrInt - 1, marsYrInt], {i, 0, 80, 1}]
Accumulate@mYrLen


Then I would need to join the two lists, but can this be done within one "step", eg. within the table?

Also, would it be possible to use this Accumulate within the Table to control the upper bound of the generated table - i.e. continue with the table while the accumulate of current i is smaller than a certain value.

• When you say "join the two lists" are you seeking a list of pairs of the item and its accumulation or a list with row one the items and row two the accumulation. – Edmund Sep 20 '16 at 23:41
• @Edmund are those two just a transpose? Then it would not matter. What I find more interesting is the second part, if it would be possible to generate the list only until the accumulate is smaller than certain number. In my code, I hardcoded 80 but in fact, the number of list items depends on the accumulated value. Do you think this is doable without loops? – leosenko Sep 21 '16 at 20:38

This creates mYrLen and accu = Accumulate@mYrLen "at one go"; I haven't tested its efficiency though - it might occur that you initial approach is faster.

marsYr = 686.9726;
marsYrInt = 687;
startId = {520, 585};
mYrLen = {};
accu = {0};
Do[If[(Floor[(marsYrInt - marsYr)*(i)] -
Floor[(marsYrInt - marsYr)*(i - 1)] == 1) \[And] (i >
0), {AppendTo[mYrLen, marsYrInt - 1];
AppendTo[accu, Last@accu + marsYrInt - 1]}, {AppendTo[mYrLen,
marsYrInt]; AppendTo[accu, Last@accu + marsYrInt]}], {i, 0, 80, 1}]
accu = Drop[accu, 1];


Check:

accu == Accumulate@mYrLen


True

You may use FoldList.

With

foo[i_] :=
If[(Floor[(marsYrInt - marsYr)*(i)] - Floor[(marsYrInt - marsYr)*(i - 1)] == 1) ∧ (i > 0),
marsYrInt - 1,
marsYrInt
]


Then

Rest@FoldList[
With[{v = foo@#2}, {v, #1[[-1]] + v}] &,
{0, 0},
Range[80]]


Will give the list pairs of the value and the accumulation at that point in the list.

Hope this helps.