Matlab.Copying the rows n times in order [duplicat

2019-08-08 16:35发布

问题:

This question already has an answer here:

  • A similar function to R's rep in Matlab [duplicate] 4 answers

Hey I would like to do something like the following

A = [...
   1 2 3
   4 5 6
   7 8 9]

to

B = [...
   1 2 3
   1 2 3
   1 2 3
   4 5 6
   4 5 6
   4 5 6
   7 8 9
   7 8 9
   7 8 9]

But please do not advice manual things. I am writing an algorithm with inputs and matrix dimensions may change.

回答1:

There's a few ways. The simplest I think would be to use the Kronecker product:

B = kron(A, ones(3,1))

the faster but less readable solution is replication by multiplication and reshaping:

B = reshape((A(:) * ones(1,3))', 3*size(A,1),size(A,2))

or the same solution, but then using repmat:

B = reshape(repmat(A(:).',3,1), 3*size(A,1),size(A,2))


回答2:

You can also try something based on the following:

a = [1 2 3]
b = [4 5 6]
c = [7 8 9]

d = [ a; a; b; b; c; c]

e = [ repmat([a], [2, 1]) ;
      repmat([b], [2, 1]) ;
      repmat([c], [2, 1]) ] 

d and e both result in the matrix below:

=

1   2   3
1   2   3
4   5   6
4   5   6
7   8   9
7   8   9

To append more rows you can also use this for loop and see what the result is:

 e = [] 
 for i = 1:2    
      e = [ e;
            repmat([a], [2, 1]) ;
            repmat([b], [2, 1]) ;
            repmat([c], [2, 1]) ]  
 end


标签: matlab row