# Sort & Index matrix for highest values in row

12 views (last 30 days)
dan berkowitz on 16 Oct 2017
Commented: dan berkowitz on 17 Oct 2017
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 on 17 Oct 2017
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
dan berkowitz on 17 Oct 2017
thank you, jan! where would humanity be without you?

Cedric Wannaz on 17 Oct 2017
Edited: Cedric Wannaz on 17 Oct 2017
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
dan berkowitz on 17 Oct 2017

Ahmed raafat on 17 Oct 2017
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
dan berkowitz on 17 Oct 2017
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'.