MATLAB: Build a matrix of zeros with the size of the initial matrix according to indices

rebuild matrixreconstruct matrix with zeros

Hi,
I have an initial matrix M(466,504) where I extracted the 30 highest values in each row with the command:
[val,idx] = maxk(M,30,2)
I would like to get now a matrix of zeros of same size but with those 30 values at their initial position.
How could I build such a matrix ?

Best Answer

newM = zeros(size(M));
newM(sub2ind(size(M), repmat((1:size(idx, 1))', 1, size(idx, 2)), idx)) = val