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

조회 수: 1 (최근 30일)
MRC
MRC 2014년 6월 16일
편집: Sean de Wolski 2014년 6월 16일
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