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

1 view (last 30 days)
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.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 19 Sep 2012
Edited: Andrei Bobrov on 19 Sep 2012
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

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!