MATLAB: Sub2ind -> out of range subscript

MATLABout of range subscriptsub2ind

my code is give out of range subscript error how can i solve it? D=6000×1 double
d = zeros(2, 1);
d(sub2ind(size(d), D(k), 1)) = 1;

Best Answer

Your d is 2 x 1, so size(d) is [2 1] . When you use sub2ind(), the data values you provide must be within the size you provide in the second parameter.
Do not use sub2ind() to try to expand a matrix (though you can get away with it by lying about the size of the current last dimension, providing you are expanding on the last dimension.)
Since your second index is always 1 and the data from D is being used as the row number, you do not need sub2ind at all. Just use
d(D,1) = 1;