how to locate rows that has max values in r*2 matrix?

I want to get the max values in a r*2 matrix. r is input from the user. Then, I want to get the complete row(s) where the maxima are. The example here may make it clear:
x = [1 7; 0 5; 9 -1];
n = max(x, [], 1); % Return the max value of each column
>> n = [9, 7] % The max values for columns 1 and 2
but I want to return the rows of the max values, so I want the result to be:
M=[1 7; 9 -1]
The rows in matrix x change based on input from the user, but the number of columns are fixed to 2.

 채택된 답변

James Tursa
James Tursa 2016년 9월 22일
편집: James Tursa 2016년 9월 22일
E.g., assuming you always want two rows (which might be the same):
[~,rows] = max(x,[],1);
M = x(sort(rows),:);
If you don't want a row repeated, then simply add code to detect this and return only one row in that case.

댓글 수: 2

thanks, works perfect
[~,rows] = max(x,[],1);
M = x(sort(rows),:);
I think that code wont give you expected answer when you have same max number at different rows . For example for x=[1 7;0 5 ;9 -1 ; 3 7] ,above code will have M=[1 7;9 -1] as an answer. More correct answer must be M=[1 7;9 -1;3 7] . With best wishes;

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Satuk Bugrahan
Satuk Bugrahan 2016년 9월 22일
편집: Satuk Bugrahan 2016년 9월 22일
[~,rows] = max(x,[],1);
M = x(sort(rows),:);
I think that code wont give you expected answer when you have same max number at different rows . Like in my code ;
x= [1 7 ;0 5 ;9 -1;3 7];
n=max(x,[],1);
inds_1 = find(x(:,1)==n(1)) ;
[rown_1, coln_1] = ind2sub(size(x),inds_1);
inds_2 = find(x(:,2)==n(2)) ;
[rown_2, coln_2] = ind2sub(size(x),inds_2);
rowns = [rown_1 ;rown_2] ;
M=zeros(numel(rowns),2) ;
for a=1:numel(rowns)
M(a,:)=x(rowns(a),:) ;
end
The answer for this specified x matrix, M=[9 -1;1 7;3 7] . Since maximum number for second column is '7' and we have two rows with having '7' in their second column.

댓글 수: 1

Thanks Satuk for your input, I tested the code provided by James and it works for all cases I have, so it returns all the rows with highest values. Thanks again for your help and it is really appreciated

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2016년 9월 22일

댓글:

2016년 9월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by