Sorted indices in Julia (numpy argsort equivalent)

Which Julia function returns indexes sorting an array? Python Numpy uses argsort .

+6
source share
2 answers
 julia> r = rand(0:9, 5) 5-element Array{Int64,1}: 5 0 6 1 1 julia> i = sortperm(r) 5-element Array{Int64,1}: 2 4 5 1 3 julia> r[i] 5-element Array{Int64,1}: 0 1 1 5 6 
+15
source

I am not 100% I understand the question, but I suspect that what you are asking is that if you have a vector

 a = [4,8,2] 

would you like to get

 order = [2,3,1] 

If this is what you need, what I do, I use sortcols, which is a workaround

If you have a vector,

 a = [5,2,8,4,3,1] 

you create a new

 b = hcat(a, 1:length(a)) 5 1 2 2 8 3 4 4 3 5 1 6 

then you call

 c = sortrows(b, by = x -> x[1]) 1 6 2 2 3 5 4 4 5 1 8 3 

and now c [:, 2] will be the last column

  6 2 5 4 1 3 

Of course, all this can be compressed into

 sortrows(hcat(a, 1:length(a)), by = x -> x[1])[:,2] 

but I wanted to explain how it works

Im really hoping someone will put up a better way to do this if it exists

+1
source

All Articles