Matlab.Copying the rows n times in order [duplicat

2019-08-08 16:15发布

This question already has an answer here:

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.

标签: matlab row
2条回答
Evening l夕情丶
2楼-- · 2019-08-08 17:02

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
查看更多
一夜七次
3楼-- · 2019-08-08 17:16

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))
查看更多
登录 后发表回答