How to repeat the rows of a matrix by a varying number?

1 vue (au cours des 30 derniers jours)
MRC
MRC le 16 Juin 2014
Modifié(e) : Sean de Wolski le 16 Juin 2014
Hi, I have a matrix A mxn and a matrix B mx1. I want to create a matrix C which repeats each row of A by the number of times indicated in B without looping, e.g.
A=[2 1; 3 4; 5 6; 8 2]
B=[1;2;4;1]
C=[2 1; 3 4; 3 4; 5 6; 5 6; 5 6; 5 6; 8 2]
Thanks!

Réponse acceptée

Jos (10584)
Jos (10584) le 16 Juin 2014
A = [2 1; 3 4; 5 6; 8 2]
B = [1;2;4;1]
C = cell2mat(arrayfun(@(k) A(repmat(k,B(k),1),:), 1:size(A,1), 'un', 0).')

Plus de réponses (1)

Sean de Wolski
Sean de Wolski le 16 Juin 2014
Modifié(e) : Sean de Wolski le 16 Juin 2014
I'd expect a for-loop to be faster than building and converting a cell array. Here is a pure indexing approach:
A=[2 1; 3 4; 5 6; 8 2] ;
B=[1;2;4;1];
C=[2 1; 3 4; 3 4; 5 6; 5 6; 5 6; 5 6; 8 2];
idx = zeros(sum(B),1);
idx(max(1,cumsum(B))) = 1;
idx = cumsum(circshift(idx,sum(B)-find(idx,1,'last')+1));
CC = A(idx,:)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by