Sort and dims=1 for vector input

Hi,

I don’t understand why a function like sort doesn’t accept dims=1 for a vector input. Let’s take b=rand(3) for instance. sort(b) works, but sort(b,dims=1) gives an error. It means that, in a case where size(b,2) is not fixed, I have to catch when size(b,2)==1 in order to compute sort(b) instead of sort(b,dims=1). Why doesn’t sort behave like that already?

Julia treats vectors as different than n x 1 matrices. For example,

julia> x = rand(4, 1) # 4 x 1 matrix
4×1 Matrix{Float64}:
 0.5699429434936178
 0.38264907855330454
 0.2974011813965416
 0.9032771294647794

julia> sort(x; dims=1) # works fine
4×1 Matrix{Float64}:
 0.2974011813965416
 0.38264907855330454
 0.5699429434936178
 0.9032771294647794

So it’s not about if size(x,2)==1, it’s about the type of the object. Usually code where x is sometimes a vector and sometimes a matrix is avoided (it’s usually type unstable), but if y is a vector, you can reshape it to be an n x 1 matrix via

julia> y = rand(4)
4-element Vector{Float64}:
 0.2646642144471312
 0.5108444025487056
 0.17038220190741749
 0.6299368977104578

julia> reshape(y, :, 1)
4×1 Matrix{Float64}:
 0.2646642144471312
 0.5108444025487056
 0.17038220190741749
 0.6299368977104578
1 Like

Or more compact: hcat(y), although that makes a copy of y. (reshape keeps the same underlying data).

1 Like

Thanks for your answer!

Then, how do I extract a column of a matrix and avoid the automatic vector conversion? Is reshape the only built in solution?

Indexing with ranges that only contain the value of the column you want:

julia> x = rand(4,2)
4×2 Array{Float64,2}:
 0.713682  0.122839
 0.488861  0.225701
 0.742566  0.451154
 0.361401  0.851278

julia> x[:,1:1]
4×1 Array{Float64,2}:
 0.7136823322753825
 0.48886127651427835
 0.7425656894856532
 0.3614009764175452
2 Likes

Thanks!

And a similar option: indexing with a vector with one element:

julia> x = rand(4,2)
4×2 Array{Float64,2}:
 0.713682  0.122839
 0.488861  0.225701
 0.742566  0.451154
 0.361401  0.851278

julia> x[:,[1]]
4×1 Array{Float64,2}:
 0.7136823322753825
 0.48886127651427835
 0.7425656894856532
 0.3614009764175452

(The key is that if the type of the index can contain more than one value, it will return a matrix instead of a vector.)

1 Like

Can’t you just work with vectors instead of one-column matrices?

No because I work with matrices, and column matrices consist of a particular case that I have to take into account.