MATLAB Answers

Duplicate elements in array n times, where n is an array itself

68 views (last 30 days)
Oliver
Oliver on 2 Sep 2016
Commented: Oliver on 2 Sep 2016
Hi everyone,
I have two arrays of the same length and would like to duplicate each element in the first array n times, where n is the value in the second array. Example:
A = [1 2 3]
B = [2 3 1]
then C shall be = [1 1 2 2 2 3]
How can this be done? I checked the forum and tried to play around with repmat but could not get it to work.
Any help is greatly appreciated! Thanks!

  1 Comment

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 2 Sep 2016
If you have MATLAB 2015a or more recent, then use repelem:
>> repelem([1 2 3],[2 3 1])
ans =
1 1 2 2 2 3

  1 Comment

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 2 Sep 2016
A = [1 2 3]
B = [2 3 1]
C=cell2mat(arrayfun(@(x,y) repmat(x,1,y),A,B,'un',0))

  0 Comments

Sign in to comment.

Sign in to answer this question.