MATLAB: How to create a vector from two vectors

code vectorizationvector creation

I have two vectors with the same length:
A = [2 4 5 4 9 8 1 6];
B = [3 6 2 5 4 4 3 5];
Each element in vector B defines how many times the corresponding element in vector A duplicates itself. For example, here I want the final vector C to have 3 twos, 6 fours, 2 fives, 5 fours, 4 nines, 4 eights, 3 ones, and 5 sixes:
C = [2 2 2, 4 4 4 4 4 4, 5 5, 4 4 4 4 4, 9 9 9 9, 8 8 8 8, 1 1 1, 6 6 6 6 6];
I can do it with a for-loop. However in practice, vectors A and B are long. So is there a way to do this without a loop.
Thanks!

Best Answer

If you have MATLAB 2015a or more recent then use repelem:
repelem(A,B)
otherwise:
cell2mat(arrayfun(@(a,b)repmat(a,1,b),A,B,'Uni',0))
although a loop may well be faster.