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

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Jos (10584)
Jos (10584) il 16 Giu 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).')

Più risposte (1)

Sean de Wolski
Sean de Wolski il 16 Giu 2014
Modificato: Sean de Wolski il 16 Giu 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,:)

Categorie

Scopri di più su Data Type Conversion 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