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.

 Respuesta aceptada

James Tursa
James Tursa el 22 de Sept. de 2016
Editada: James Tursa el 22 de Sept. de 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 comentarios

JacobM
JacobM el 22 de Sept. de 2016
thanks, works perfect
Satuk Bugrahan
Satuk Bugrahan el 22 de Sept. de 2016
Editada: Satuk Bugrahan el 22 de Sept. de 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;

Iniciar sesión para comentar.

Más respuestas (1)

Satuk Bugrahan
Satuk Bugrahan el 22 de Sept. de 2016
Editada: Satuk Bugrahan el 22 de Sept. de 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 comentario

JacobM
JacobM el 23 de Sept. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Preguntada:

el 22 de Sept. de 2016

Comentada:

el 23 de Sept. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by