Hi I need to select n number of rows that in some column have the highest values
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Lets say I have to select 2 values and select the highest from colum three
a=[1,2,3;4,5,6;7,8,9]
then my answer would be
b=[4,56;7,8,9]
0 comentarios
Respuestas (1)
Star Strider
el 3 de Jun. de 2016
This works:
a=[1,2,3;4,5,6;7,8,9]
[C3, I] = sort(a(:,3),'ascend');
B = a(I(end-1:end),:)
B =
4 5 6
7 8 9
2 comentarios
Star Strider
el 3 de Jun. de 2016
My pleasure.
For the one highest value in a specific column, for example column 2, the ‘B’ assignment becomes:
[C3, I] = sort(a(:,2),'ascend');
B = a(I(end),:)
You could also use the max function with two outputs instead of sort if you only want one value. I used sort here to give you flexibility. Note that using the 'descend' argument with sort keeps the rows in the order you initially wanted them.
Also, you don’t have to return ‘C3’ here. You could suppress it by using a tilde (~). I used it here to be certain the row returned was the correct one.
That call would be:
[~,I] = sort(a(:,2),'ascend');
I just present this to provide an inclusive way of calling the functions.
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!