Reputation: 2805
I want to do a sum over one dimension in an array. That's easy. For an array 9x100x100:
sum(a,1)
However what is then left is an array with dimension 1x100x100. And now I want to get rid of the first dimension, since there is only one element left. So my solution is just:
reshape(summed_array, 100,100)
In order to get the 100x100 array, which I wanted. However this does not feel very clean. Is there a better way of achieving this?
Upvotes: 7
Views: 3052
Reputation: 66244
As @E_net4 points out in a comment below, since Julia 1.0, you should use dropdims
(a much better name!) rather than squeeze
.
You're looking for squeeze
:
squeeze(A, dims)
Remove the dimensions specified by dims from array
A
. Elements ofdims
must be unique and within the range1:ndims(A)
.
julia> a = rand(4,3,2)
4x3x2 Array{Float64,3}:
[:, :, 1] =
0.333543 0.83446 0.659689
0.927134 0.885299 0.909313
0.183557 0.263095 0.741925
0.744499 0.509219 0.570718
[:, :, 2] =
0.967247 0.90947 0.715283
0.659315 0.667984 0.168867
0.120959 0.842117 0.217277
0.516499 0.60886 0.616639
julia> b = sum(a, 1)
1x3x2 Array{Float64,3}:
[:, :, 1] =
2.18873 2.49207 2.88165
[:, :, 2] =
2.26402 3.02843 1.71807
julia> c = squeeze(b, 1)
3x2 Array{Float64,2}:
2.18873 2.26402
2.49207 3.02843
2.88165 1.71807
Upvotes: 11