issue using 'sort'
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
KSSV
el 17 de Mzo. de 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 ])
Respuestas (2)
Walter Roberson
el 17 de Mzo. de 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 comentarios
Stephen23
el 17 de Mzo. de 2022
Editada: Stephen23
el 17 de Mzo. de 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 comentarios
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!