Jeff
Jeff

Reputation: 1242

Efficient one-liner in Julia to calculate "running" sums?

Is there an efficient way to do the following in Julia in one line of code?

foldl((prev, x)-> [prev; prev[end] + x] , 0, block_lengths)

For example, for

block_lengths = [2, 2, 2, 2, 3]

the desired output is

[0, 2, 4, 6, 8, 11]

(I presume that the way I used foldl above is inefficient, because I'm concatenating a vector and an integer at each iteration.)

Upvotes: 1

Views: 517

Answers (1)

DSM
DSM

Reputation: 353569

IIUC, you can use cumsum:

julia> block_lengths = [2, 2, 2, 2, 3];

julia> cumsum(block_lengths)
5-element Array{Int32,1}:
  2
  4
  6
  8
 11

julia> [0; cumsum(block_lengths)]
6-element Array{Int32,1}:
  0
  2
  4
  6
  8
 11

which should be O(N).

Upvotes: 4

Related Questions