Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum over a dimension in array while dropping the traversed dimension?

Tags:

arrays

julia

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?

like image 586
hr0m Avatar asked Aug 06 '16 16:08

hr0m


People also ask

What does dimension of array mean?

A dimension is a direction in which you can vary the specification of an array's elements. An array that holds the sales total for each day of the month has one dimension (the day of the month).


1 Answers

Update

As @E_net4 points out in a comment below, since Julia 1.0, you should use dropdims (a much better name!) rather than squeeze.

Original answer

You're looking for squeeze:

squeeze(A, dims)

Remove the dimensions specified by dims from array A. Elements of dims must be unique and within the range 1:ndims(A).

Example

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
like image 100
jub0bs Avatar answered Sep 23 '22 04:09

jub0bs