issue using 'sort'
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
KSSV
am 17 Mär. 2022
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 ])
Antworten (2)
Walter Roberson
am 17 Mär. 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)
0 Kommentare
Stephen23
am 17 Mär. 2022
Bearbeitet: Stephen23
am 17 Mär. 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
[~,Y] = sort(X) % what you want
0 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!