MATLAB: How to expand a vector by a different number of copies for each entry

expansionvector

I want to expand a vector in such a way that each entry is repeated a different number of times. SAy I have a data vector A=[1;2;3;4;5] and a vector of the same size that specifies the number of times each entry in A is to be extended by, B=[2;1;3;1;3]. That is I want to create C=[1;1;2;3;3;3;4;5;5;5].
Is there any slick way to do this without coding a loop? I understand that R2015a introduced a command "repelem" that could take care of this. Unfortunately, I am using R2013b.

Best Answer

A=[1;2;3;4;5];
B=[2;1;3;1;3];
n = cumsum(B);
idx = zeros(n(end),1);
idx(cumsum(B)-B+1) = 1;
C = A(cumsum(idx));