I have
a = ["B", "C", "A"]
and
b = [7, 10, 5]
How can I sort a by the order of the elements of b?
So, to explain, the order of the elements in b is the indexes of the sorted elements ([3,1,2]). I would like to use that to do this:
a[[3,1,2]]
["A", "B", "C"]
You are looking for sortperm:
sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)Return a permutation vector
Ithat putsv[I]in sorted order. The order is specified using the same keywords assort!. The permutation is guaranteed to be stable even if the sorting algorithm is unstable, meaning that indices of equal elements appear in ascending order.
Applied to your example:
julia> a = ["B", "C", "A"]
3-element Array{String,1}:
"B"
"C"
"A"
julia> b = [7, 10, 5]
3-element Array{Int64,1}:
7
10
5
julia> perm = sortperm(b)
3-element Array{Int64,1}:
3
1
2
julia> a[perm]
3-element Array{String,1}:
"A"
"B"
"C"
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