Strange behavior of "sort" function

조회 수: 4 (최근 30일)
Alain LESTRADE
Alain LESTRADE 2020년 4월 11일
답변: Alain LESTRADE 2020년 4월 11일
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.

채택된 답변

Stephen23
Stephen23 2020년 4월 11일
편집: Stephen23 2020년 4월 11일
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.

추가 답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 4월 11일
편집: Ameer Hamza 2020년 4월 11일
sort() function does not provide any function to get back the original vector. The first example you gave was just a coincidence. The actual working of idx output of sort is like this
>> A = [5 8 91 19]
A =
5 8 91 19
>> [out,idx] = sort(A)
out =
5 8 19 91
idx =
1 2 4 3
>> A(idx) % <---- idx is used to get sorted vector from origina.
ans =
5 8 19 91
To get the original vector back, you need to call sort twice
A = [5 8 4 19 1];
[out,idx] = sort(A);
[~,idx2] = sort(idx);
out(idx2)
ans =
5 8 4 19 1
  댓글 수: 2
Stephen23
Stephen23 2020년 4월 11일
편집: Stephen23 2020년 4월 11일
"sort() function does not provide any function to get back the original vector."
Can you please clarify this statement? The two outputs contain enough information to recreate the original vector with one use of basic indexing, nothing else is required.
"To get the original vector back, you need to call sort twice"
No, you do NOT "need" to call sort twice. The two outputs of sort are enough, using basic indexing.
Ameer Hamza
Ameer Hamza 2020년 4월 11일
Correct. I missed this point. I was pointing the mistake in OPs reasoning and overlooked this simple approach.

댓글을 달려면 로그인하십시오.


Alain LESTRADE
Alain LESTRADE 2020년 4월 11일
First of all, I would like to thank everybody for your prompt answers.
Both proposals are right for me, Stephen's one is shorter and then more elegant.
See you later on Matlab guys!

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by