Efficient way to sum an array of integers in Julia

I have a 2D array that I want to modify to summarize a given element in a row with all the elements in front of it, for example, if I have an array:

[1 2; 3 6; 4 7; 4 8] 

I want to convert it to

 [1 2; 4 8; 8 15; 12 23] 

I can do this using the following snippet in julia:

 for i in 1:10, for k in 2:size(d,1), d([k,i] += d[k-1,i)]; end end 

But I suppose there should be a more efficient way to do this?

+6
source share
2 answers

Yes there is: cumsum

 julia> d = [1 2; 3 6; 4 7; 4 8] 4x2 Array{Int64,2}: 1 2 3 6 4 7 4 8 julia> cumsum(d) 4x2 Array{Int64,2}: 1 2 4 8 8 15 12 23 
+16
source

According to a comment by @tholy, the amazing thing about julia is that the built-in functions are not special and are not faster than custom ones. They are both fast. I changed your function and I got it to execute in much the same way as the built-in cumsum :

 function testA!(arr) @inbounds for i in 1:size(arr, 2) tmp = arr[1, i] for k in 2:size(arr,1) tmp += arr[k, i] arr[k,i] = tmp end end arr end function testB!(arr) cumsum!(arr, arr) end 

I built test arrays:

 arr = rand(1:100, 10^5, 10^2) arr2 = copy(arr) 

and I got the following timings:

 @time testA!(arr) 0.007645 seconds (4 allocations: 160 bytes) @time testB!(arr2) 0.007704 seconds (4 allocations: 160 bytes) 

which are basically equivalent.

+5
source

All Articles