This kind of question has been asked and answered on many occasions, but I can’t seem to find a good duplicate.
Regardless, you would use the second output of sort
on the rank
vector to give you the position of where each value would appear in the sorted result. Specifically, for each value in the second output of sort
, it would tell you which value in the original vector you would have to grab to place it in this corresponding position to sort the data.
You would then use this ordering to index into your data to get the right and desired ordering.
Specifically:
x=[ 3 7 2 0 5 2];
ranks = [3 5 2 1 4 2];
[~,ind] = sort(ranks);
out = x(ind);
We get for out
:
out =
0 2 2 3 5 7
You can verify that we are pulling out values in the data that respect the sorted order seen in ranks
.