Which Julia's function returns the indexes that would sort an array? Python's Numpy uses argsort
.
You sort the list by passing it to sorted and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...] list comprehension.
Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.
We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword.
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
Im not 100% I understand the question, but I suspect that what you are asking, is that if you have the vector
a = [4,8,2]
you would like to get
order = [2,3,1]
If that's what you need, what I do is I use sortcols, which is a veird 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 latter column
6
2
5
4
1
3
Ofcourse, this can all be compressed into
sortrows(hcat(a, 1:length(a)), by = x -> x[1])[:,2]
but I felt like explaining how it works
Im really hoping someone posts a better way to do this, if one exists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With