N=[2;3;4;2;4;1;4;3;2;1];
M = repelem((1:numel(N))', N)
If you were to use a loop to generate M, the most efficient way would probably be:
startidx = cumsum([1; N]);
M = zeros(sum(N), 1);
for idx = 1:numel(N)
M(startidx(idx) : startidx(idx)+N(idx)-1) = idx;
end