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.
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!