Sort & Index matrix for highest values in row

3 ビュー (過去 30 日間)
dan berkowitz
dan berkowitz 2017 年 10 月 16 日
コメント済み: dan berkowitz 2017 年 10 月 17 日
Hi, I have a 5 x 5 matrix, A.
How can I create a matrix that has 1's for the largest two values in each row, and all remaining elements are zero? (I created a sort index by sort(A,2,'descend)...but am lost...).
The output matrix is a 5 x 5 matrix with 1's for the largest two values in each row.
Any help would be appreciated. Thanks!
Dan

採用された回答

Jan
Jan 2017 年 10 月 17 日
x = randi([0,20], 5, 5);
[~, index] = sort(x, 2, 'descend'); % Sorting index
result = zeros(size(x)); % Create output
result(sub2ind(size(x), 1:5, index(:, 1).')) = 1; % Mark largest
result(sub2ind(size(x), 1:5, index(:, 2).')) = 1; % Mark 2nd largest
  1 件のコメント
dan berkowitz
dan berkowitz 2017 年 10 月 17 日
thank you, jan! where would humanity be without you?

サインインしてコメントする。

その他の回答 (2 件)

Cedric
Cedric 2017 年 10 月 17 日
編集済み: Cedric 2017 年 10 月 17 日
Here is another way:
>> A = rand(5, 5)
A =
0.9337 0.1518 0.6164 0.3074 0.4584
0.9017 0.1290 0.8862 0.4706 0.3778
0.6309 0.8430 0.3314 0.1133 0.3268
0.8527 0.1393 0.8076 0.4477 0.7315
0.4614 0.8630 0.6206 0.1753 0.5531
>> idm = A == max(A, [], 2) ;
A(idm) = NaN ;
B = double( A == max(A, [], 2) | idm )
B =
1 0 1 0 0
1 0 1 0 0
1 1 0 0 0
1 0 1 0 0
0 1 1 0 0
If you have more than one max or more than one second max, you will get more than two 1 per row though. If you need to make a choice (e.g. pick the left-most occurrences), you will need to implement more logic/sorting. See below what I mean:
>> A = randi(10, 5, 5)
A =
9 3 6 5 10
9 8 9 1 10
4 5 8 2 7
1 9 9 10 9
6 7 5 4 4
>> idm = A == max(A, [], 2) ;
A(idm) = NaN ;
B = double( A == max(A, [], 2) | idm )
B =
1 0 0 0 1
1 0 1 0 1
0 0 1 0 1
0 1 1 1 1
1 1 0 0 0
  1 件のコメント
dan berkowitz
dan berkowitz 2017 年 10 月 17 日
thx. appreciate your help!

サインインしてコメントする。


Ahmed raafat
Ahmed raafat 2017 年 10 月 17 日
you mean you want only first high values in each row right??
y=zeros(size(A,1),size(A,2));
for i=1:size(A,1)
x=sort(A(i,:),descend');
y(i,1:2)=x(1:2);
end
  1 件のコメント
dan berkowitz
dan berkowitz 2017 年 10 月 17 日
No. I want the output to be a 5x5 matrix. And there should be '1' in each row where the largest two values are. All other entries in the matrix should be '0'.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by