# How to create a vector from two vectors?

27 views (last 30 days)
DS Chen on 30 Aug 2016
Commented: DS Chen on 30 Aug 2016
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!

Stephen Cobeldick on 30 Aug 2016
Edited: Stephen Cobeldick on 30 Aug 2016
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.

DS Chen on 30 Aug 2016
Is repelem(A,B) in 2015a faster than for-loop?
I'm using 2013b. I guess I'll use for-loop then.
Thank you!
Stephen Cobeldick on 30 Aug 2016
Important: do NOT expand the array in the loop! Use a preallocated cell array:
>> C = cell(size(A));
>> for k = 1:numel(C), C{k} = repmat(A(k),1,B(k)); end
>> cell2mat(C)
Or a preallocated numeric array (this is faster):
>> X = cumsum([0,B]);
>> D = NaN(1,X(end));
>> for k = 1:numel(A), D(1+X(k):X(k+1)) = A(k); end
DS Chen on 30 Aug 2016
Good Point!
Using preallocated cell array is 40 times faster than expanding array in the loop.
I also test the repelem(A, B) on the other machine. repelem(A,B) is indeed the fastest! It's at least 10 times faster than for-loop. I hope I can use it later:)