MATLAB Answers

0

Sort Index - Bug

Asked by Rainer Ng on 19 Sep 2019 at 21:08
Latest activity Commented on by Rainer Ng on 19 Sep 2019 at 21:42
[a, sort_index]=sort([100;20;30;40])
The sort_index should return
4
1
2
3
But it does not.

  0 Comments

Sign in to comment.

Tags

Products


Release

R2018b

2 Answers

Walter Roberson
Answer by Walter Roberson
on 19 Sep 2019 at 21:31
 Accepted Answer

>> [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);

  0 Comments

Sign in to comment.


James Tursa
Answer by James Tursa
on 19 Sep 2019 at 21: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 Comment

Rainer Ng on 19 Sep 2019 at 21:42
I apologize. I should have understood this. Thank you.

Sign in to comment.