Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does `sum` on a Matrix return Matrix, not Vector?

Tags:

If I do

mat = rand(8,8)
sum(mat, 1)

the return type is a Matrix with a single row, whereas sum(mat, 2) gives a Matrix with a single column. This surprises me, as singleton dimensions are generally dropped in 0.5, so I would expect the return type of both operations would be a Vector. Why is the singleton dimension not dropped here?

I might expect this was in order to preserve the orientation (e.g. sum(mat, 1) is a row Vector), but the behaviour is the same on 0.6, which has explicit 1-d RowVectors, so this does not appear to be an explanation.

Thanks!

like image 430
Michael K. Borregaard Avatar asked Feb 20 '17 19:02

Michael K. Borregaard


1 Answers

Yes, reductions like sum preserve the dimensionality of the array. This is intentional as it enables broadcasting the result back across the original array. This means that you can, for example, normalize the columns of an array with ./:

julia> A = rand(1:100, 4, 3)
4×3 Array{Int64,2}:
 94  50  32
 46  15  78
 34  29  41
 79  22  58

julia> A ./ sum(A, 1)
4×3 Array{Float64,2}:
 0.371542  0.431034  0.15311
 0.181818  0.12931   0.373206
 0.134387  0.25      0.196172
 0.312253  0.189655  0.277512

While the two-dimensional case might be able to be handled by RowVectors, that approach does not generalize to higher dimensions.

That said, there are other cases where dropping dimensions would be similarly useful. This is an open design question on the issue tracker.

like image 126
mbauman Avatar answered Sep 21 '22 10:09

mbauman