issue using 'sort'

12 views (last 30 days)
Mohammed Raslan
Mohammed Raslan on 17 Mar 2022
Edited: Stephen23 on 17 Mar 2022
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 Comment
KSSV
KSSV on 17 Mar 2022
Why it is not correct?
B = [ 4.519 ; 2.2325 ; 2.6582 ; 3.4591 ; 3.3404 ];
[aB,bB] = sort(B);
aB
aB = 5×1
2.2325 2.6582 3.3404 3.4591 4.5190
The order is correct. What made you tell it is wrong? See the order you specified.
B([ 5 ; 1 ; 2 ; 4 ; 3 ])
ans = 5×1
3.3404 4.5190 2.2325 3.4591 2.6582

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 17 Mar 2022
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)

Stephen23
Stephen23 on 17 Mar 2022
Edited: Stephen23 on 17 Mar 2022
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
X = 5×1
2 3 5 4 1
[~,Y] = sort(X) % what you want
Y = 5×1
5 1 2 4 3

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!