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

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.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2015년 11월 17일
편집: Andrei Bobrov 2015년 11월 17일
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));

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 11월 17일

댓글:

2015년 11월 17일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by