MATLAB: Repeating elements of a vector

MATLABrepeating vector values

I have two vectors, say lambda=[1; 2] and ng=[3;4]. I want to have a long vector where the elements of lambda are repeated the corresponding times of the values of ng, i.e., I want to get
lambda_long=[1;1;1;2;2;2;2]
I can do it with some for loop, but is there any other efficient way of doing this?

Best Answer

Fully vectorized run-length decoding:
% Example inputs (as vector columns)
lambda = [2; 4;9];
ng = [3;4;7];
% Preallocate output
out = zeros(sum(ng),1);
% Distribute starting point of sequences
csng = cumsum(ng);
out([1; csng(1:end-1)+1]) = [lambda(1); diff(lambda)];
% Propagate
out = cumsum(out)