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

1 visualización (últimos 30 días)
MRC
MRC el 16 de Jun. de 2014
Editada: Sean de Wolski el 16 de Jun. de 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!

Respuesta aceptada

Jos (10584)
Jos (10584) el 16 de Jun. de 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).')

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 16 de Jun. de 2014
Editada: Sean de Wolski el 16 de Jun. de 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,:)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by