Hi I need to select n number of rows that in some column have the highest values

1 次查看(过去 30 天)
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]

回答(1 个)

Star Strider
Star Strider 2016-6-3
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 个评论
Hansel Montuffar
Hansel Montuffar 2016-6-3
Thanks for answering but how do I modify that to search for th highest value in a specific column?
Star Strider
Star Strider 2016-6-3
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by