how to locate rows that has max values in r*2 matrix?
1 回表示 (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
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 件のコメント
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 . 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
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.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!