How to duplicate rows of a matrix if the number of copies for each row are different?
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi all,
I want to duplicate each rows of a matrix according to the numbers given in a vector.
For example, I have matrix A and vector
, I want to duplicate the first row of A 2 times, second row by 4 times and third row by 5 times.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/794749/image.png)
Is there any way to do this?
Thank you for your help.
0 Commenti
Risposta accettata
Stephen23
il 9 Nov 2021
Modificato: Stephen23
il 9 Nov 2021
out = repelem(A,b,1)
Più risposte (2)
Sulaymon Eshkabilov
il 9 Nov 2021
It can be done in a few different ways, e.g.:
A = magic(3)
b = [2, 4, 5];
AA = [repmat(A(1,:), b(1),1);repmat(A(2,:), b(2),1); repmat(A(3,:), b(3),1)]
% Alternative way:
A = magic(3);
b = [2, 4, 5];
AA =[];
for ii = 1:numel(b)
AA = [AA; repmat(A(ii,:), b(ii),1)];
end
AA
2 Commenti
Sulaymon Eshkabilov
il 9 Nov 2021
I don't believe there is an alternative more efficient way than using [for .. end] or [while .. end] loop.
Vedere anche
Categorie
Scopri di più su Matrix Indexing 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!