MATLAB: Extract top 10 values from each row

indicesmaximumtop values

Hello,
I have a matrix and wish to keep only the top 10 values in each row and replace all the other (bottom 90) values with zeros. Is there an efficient way to achieve this?

Best Answer

[sortvals, sortidx] = sort(A,'descend');
B = zeros(size(A),class(A));
for K = 1 : size(A,2)
B(sortidx(1:10,K),K) = sortvals(1:10,K);
end
Yes, it could probably be done without a loop, using sub2ind(), but that would not necessarily be any faster, and would probably be less clear.