Given two vectors A and B, what is the best way to generate the vector C such that sum(C==A(i)) = B(i)?

Example
If
A = [1 2 3]
B = [2 4 6]
then
C = [1 1 2 2 2 2 3 3 3 3 3 3]
Obviously, this can be done in a for-loop, but I want to know if there is a vector manipulation trick I am missing that could do this more efficiently.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 9월 19일
편집: Andrei Bobrov 2012년 9월 19일
A = [1 2 3];
B = [2 4 6];
i2 = cumsum(B);
idx = zeros(1,i2(end));
idx(i2 - B + 1) = 1;
C = A(cumsum(idx));
or
C = cell2mat(arrayfun(@(x,y)x(ones(1,y)),A,B,'un',0));
or
i2 = cumsum(B);
i1 = i2 - B + 1;
C = zeros(1,i2(end));
for jj = 1:numel(A)
C(i1(jj):i2(jj)) = repmat(A(jj),1,B(jj));
end

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by