Reputation: 8117
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
?
Upvotes: 3
Views: 321
Reputation: 69949
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.
Upvotes: 6
Reputation: 1390
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
.
Upvotes: 7