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 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Andrei Bobrov
il 19 Set 2012
Modificato: Andrei Bobrov
il 19 Set 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!