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]
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!