Generating a long vector from two other vectors

3 visualizzazioni (ultimi 30 giorni)
Shoaibur Rahman il 22 Lug 2015
Commentato: Shoaibur Rahman il 22 Lug 2015
I got stuck with a (may be) simple problem. Here are two vectors, like:
a = [20 13 24 ...];
b = [3 2 4 ...];
How can I create a new vector that contains 3 20s, 2 13s, 4 24s, and so on? (Not using any loop). The output will look like as shown in c:
c =
20 20 20 13 13 24 24 24 24 ...
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

Azzi Abdelmalek il 22 Lug 2015
Modificato: Azzi Abdelmalek il 22 Lug 2015
a = [20 13 24 ];
b = [3 2 4 ];
out=cell2mat(arrayfun(@(x,y) repmat(x,1,y),a,b,'un',0))
or with a for loop
a = [20 13 24 ];
b = [3 2 4 ];
out=zeros(1,numel(a))
c=[ 0 cumsum(b)]
for k=1:numel(a)
out(c(k)+1:c(k+1))=a(k)*ones(1,b(k))
end
1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Shoaibur Rahman il 22 Lug 2015
Thanks a lot. It works. I read the docs of functions you have used, but was not clear about how it is working. Could you please explain the the command in brief ( out=cell2mat(arrayfun(@(x,y) repmat(x,1,y),a,b,'un',0)) )?

Accedi per commentare.

Più risposte (1)

Steven Lord il 22 Lug 2015
v = repelem([20 13 24], [3 2 4])
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Categorie

Scopri di più su Code Generation in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by