MATLAB: Sort & Index matrix for highest values in row

sort

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

Best Answer

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