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.
채택된 답변
추가 답변 (1개)
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.
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!