Broadcast over Array Dimension

Viewed 131

Let's say I have a two-dimensional array

a = [1 2 3; 1 2 3]

2×3 Array{Int64,2}:
 1  2  3
 1  2  3

and I would like sum along a dimension, e.g. along dimension 1 yielding

[2, 4, 6]

or along dimension 2 yielding

[6, 6]

How is this done properly in Julia?

2 Answers
julia> sum(a; dims=1)
1×3 Array{Int64,2}:
 2  4  6

julia> sum(a; dims=2)
2×1 Array{Int64,2}:
 6
 6

You can drop the dimension with vec.

What Jun Tian suggests is the standard way to do it. However, it is also worth to know a more general pattern:

julia> sum.(eachrow(a))
2-element Array{Int64,1}:
 6
 6

julia> sum.(eachcol(a))
3-element Array{Int64,1}:
 2
 4
 6

In this case sum can be replaced by any collection aggregation function.

Related