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

13 views (last 30 days)
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.

Accepted Answer

James Tursa
James Tursa on 22 Sep 2016
Edited: James Tursa on 22 Sep 2016
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 Comments
Satuk Bugrahan
Satuk Bugrahan on 22 Sep 2016
Edited: Satuk Bugrahan on 22 Sep 2016
[~,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;

Sign in to comment.

More Answers (1)

Satuk Bugrahan
Satuk Bugrahan on 22 Sep 2016
Edited: Satuk Bugrahan on 22 Sep 2016
[~,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 Comment
JacobM
JacobM on 23 Sep 2016
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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!