issue using 'sort'
12 次查看(过去 30 天)
显示 更早的评论
Hi,
I have an issue using 'sort.' It is not giving the correct order of the vector.
Below are the two lines I use:
B = [ 4.519 ; 2.2325 ; 2.6582 ; 3.4591 ; 3.3404 ];
[aB,bB] = sort(B);
Below are the results:
aB = [ 2.2325 ; 2.6582 ; 2.6582 ; 3.3404 ; 4.5193 ];
bB = [ 2 ; 3 ; 5 ; 4 ; 1 ];
bB can not be correct. How come?
bB should be = [ 5 ; 1 ; 2 ; 4 ; 3 ];
1 个评论
KSSV
2022-3-17
Why it is not correct?
B = [ 4.519 ; 2.2325 ; 2.6582 ; 3.4591 ; 3.3404 ];
[aB,bB] = sort(B);
aB
The order is correct. What made you tell it is wrong? See the order you specified.
B([ 5 ; 1 ; 2 ; 4 ; 3 ])
回答(2 个)
Walter Roberson
2022-3-17
You are expecting that the second output of sort() will tell you where each element of the input goes in the output. You are expecting that the first element will be 5 because B(1) moves to position 5.
However, what sort returns is the order that things came from. The first element will be 2 because B(2) moves to become first (least magnitude).
With the current output, you can know immediately where the smallest value is located in the input vector: the first element of the second output tells you; likewise the last element of the second output tells you immediately where the largest value is located in the input vector.
With your proposed output, in order to find the location of the smallest value in the input vector, you would have to search the result looking for 1
find(bB==1)
0 个评论
Stephen23
2022-3-17
编辑:Stephen23
2022-3-17
The output is correct: just as the SORT documentation states, the second output is the index such that the first output can be obtained using that index: out = B(X).
What you want is easy to obtain from that:
B = [4.519;2.2325;2.6582;3.4591;3.3404];
[~,X] = sort(B) % correct output
[~,Y] = sort(X) % what you want
0 个评论
另请参阅
类别
在 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!