Hi I need to select n number of rows that in some column have the highest values
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Star Strider
am 3 Jun. 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 Kommentare
Star Strider
am 3 Jun. 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.
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!