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

1 次查看(过去 30 天)
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!

采纳的回答

Jos (10584)
Jos (10584) 2014-6-16
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).')

更多回答(1 个)

Sean de Wolski
Sean de Wolski 2014-6-16
编辑:Sean de Wolski 2014-6-16
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,:)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by