Sort Index - Bug
5 次查看(过去 30 天)
显示 更早的评论
[a, sort_index]=sort([100;20;30;40])
The sort_index should return
4
1
2
3
But it does not.
0 个评论
采纳的回答
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
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
2021-4-14
I never got that output; which code were you using, and which MATLAB version?
更多回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!