MATLAB: Strange behavior of “sort” function

sort

Hello,
The sort function is used as follows:
>> [out,idx] = sort([5 8 91 19])
out =
5 8 19 91
idx =
1 2 4 3
If we need to rearrange the vector later in the code with the previous order, it's possible with that set of figures to write:
>> out(idx)
ans =
5 8 91 19 % is equal to the original vector [5 8 91 19]
All is fine…
But, can you explain why it does'nt work in the same way for the following set :
>> [out,idx] = sort([5 8 4 19])
out =
4 5 8 19
idx =
3 1 2 4
>> out(idx)
ans =
8 4 5 19 % is different from the original vector [5 8 4 19]
I thank you in advance for your answer, I really need to implement that idea of using out(idx) in my code.

Best Answer

Your first example is just a coincidence, but that is NOT the correct way to get the original vector order.
The correct way to get back the original vector order is like this:
>> out(idx) = out
out =
5 8 4 19
Note that the LHS can be any array of a suitable size, I just used out for convenience.