5
$\begingroup$

I have pairs of numbers {a1, b1}, {a2, b2}, {a3, b3}, ..., {aN, bN}

What is the shortest way to compute and plot {a1, b1}, {a2, b1+b2}, {a3, b1+b2+b3},....?

$\endgroup$
2
  • 3
    $\begingroup$ {as, bs} = Transpose[pairs]; result = Transpose[{as, Accumulate[bs]}] $\endgroup$
    – user484
    Nov 14 '15 at 5:08
  • 1
    $\begingroup$ Or, Transpose[MapAt[Accumulate, Transpose[pairs], 2]]. $\endgroup$
    – J. M.'s torpor
    Nov 14 '15 at 7:20
13
$\begingroup$
Accumulate@Array[b, {3}]
(* {b[1], b[1] + b[2], b[1] + b[2] + b[3]} *)

therefore:

{a, b} = Transpose[list];
Transpose[{a, Accumulate[b]}]

Also this will do the job:

Rest@FoldList[{#2[[1]], #1[[2]] + #2[[2]]} &, {0, 0}, list]

or even easier

list[[All,2]]=Accumulate@list[[All,2]]; list
$\endgroup$
10
$\begingroup$
FoldList[{0, 1} # + #2 &, list]
$\endgroup$
5
$\begingroup$

thanks to Mike Honeychurch, without pure function:

list = {{a1, b1}, {a2, b2}, {a3, b3}};
Thread[{Thread[list][[1]], Rest@FoldList[Plus, 0, Thread[list][[2]]]}]
(* {{a1, b1}, {a2, b1 + b2}, {a3, b1 + b2 + b3}} *)

and shorter (one expression):

Thread[{list[[All, 1]], Accumulate[list][[All, 2]]}]
$\endgroup$
2
  • $\begingroup$ Could you please explain a little bit more how Rest@FoldList structure works? $\endgroup$
    – Mary
    Nov 14 '15 at 17:30
  • 1
    $\begingroup$ @Maria. Rest just removes first element in the list, i.e. Rest[{1, 2, 3}] gives {2, 3}. @ is a shorthand for head application. So Rest@FoldList[...] is the same as Rest[FoldList[...]]. Finally, FoldList[Plus, 0, {a, b, c}] gives {0, a, a + b, a + b + c}. Now you may see why we need Rest - just to get rid of 0. $\endgroup$
    – garej
    Nov 14 '15 at 17:55

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.