Sort & Index matrix for highest values in row

4 次查看(过去 30 天)
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

更多回答(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

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 CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by