A = randi(9,6,20)
N = 10;
[B,C] = sort(A,2);
B(:,1:end-N) = 0;
R = (1:size(B,1))'*ones(1,size(B,2));
Z = zeros(size(B));
Z(sub2ind(size(B),R,C)) = B
Where the example input and output matrix is:
A =
5 6 7 4 6 5 5 9 3 2 5 7 5 2 1 8 4 9 5 4
9 3 8 5 7 4 3 2 5 5 8 5 3 6 5 2 9 6 4 7
5 9 5 9 3 8 3 5 2 3 8 4 2 9 1 5 4 6 5 9
4 6 8 7 5 7 3 4 5 1 7 6 8 7 8 5 8 6 6 6
3 2 7 5 6 1 8 4 8 6 2 2 5 8 5 9 9 1 5 2
7 8 6 6 1 4 3 1 5 3 5 7 7 7 8 7 6 6 7 9
Z =
0 6 7 0 6 0 0 9 0 0 5 7 5 0 0 8 0 9 5 0
9 0 8 0 7 0 0 0 0 0 8 5 0 6 5 0 9 6 0 7
0 9 0 9 0 8 0 5 0 0 8 0 0 9 0 5 0 6 5 9
0 0 8 7 0 7 0 0 0 0 7 0 8 7 8 0 8 0 6 6
0 0 7 0 6 0 8 0 8 6 0 0 0 8 5 9 9 0 5 0
7 8 0 0 0 0 0 0 0 0 0 7 7 7 8 7 0 6 7 9
Note that picking the largest ten values may have unintended side effects: the code above picks the first of identical values, which means although one value might exist in multiple locations in one row, it is possible that only the first ones get returned (e.g 5 in the first row: there are actually six of them in the original matrix, but only three in the output). By "filtering" based on value rather than number of occurrences you could avoid this problem.
Best Answer