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

4 ビュー (過去 30 日間)
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 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by