Sort Index - Bug

조회 수: 6 (최근 30일)
Rainer Ng
Rainer Ng 2019년 9월 19일
댓글: Walter Roberson 2021년 4월 14일
[a, sort_index]=sort([100;20;30;40])
The sort_index should return
4
1
2
3
But it does not.

채택된 답변

Walter Roberson
Walter Roberson 2019년 9월 19일
>> [a, sort_index]=sort([100;20;30;40])
a =
20
30
40
100
sort_index =
2
3
4
1
This output is correct. It tells you that a(1) == 20 came from element #2 of the input, and that a(2) == 30 came from element 3 in the input, and that a(3) == 40 came from element 4 of the input, and that a(4) == 100 came from element 1 of the input.
To get the output you want, use
b(sort_index) = 1:length(sort_index);
  댓글 수: 4
Franziska Höppe
Franziska Höppe 2021년 4월 13일
Thank you for you detailed answer! :-)
The issue is if you let run the loop, you get a different result. You get:
2
5
2
Do you know why?
Walter Roberson
Walter Roberson 2021년 4월 14일
I never got that output; which code were you using, and which MATLAB version?

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

추가 답변 (1개)

James Tursa
James Tursa 2019년 9월 19일
The sort index gives the location in the original array of the sorted values. I.e., the sort results "a" are "original_array(sort_index)"
>> x = [100;20;30;40];
>> [a,sort_index] = sort(x)
a =
20
30
40
100
sort_index =
2
3
4
1
>> x(sort_index)
ans =
20
30
40
100
>> isequal(x(sort_index),a)
ans =
1
  댓글 수: 1
Rainer Ng
Rainer Ng 2019년 9월 19일
I apologize. I should have understood this. Thank you.

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

카테고리

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

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by