Repmat the rows of a matrix

8 次查看(过去 30 天)
Luis Isaac
Luis Isaac 2016-1-20
回答: Jordan Lui 2020-12-2
Dear;
I would like to efficiently repmat the rows of a matrix to for a new one; For example the matrix:
A=[2 0 0;
0 2 0;
0 0 2;
];
I want to replicate 3 times the rows to form the following matrix:
B=[2 0 0;
2 0 0;
2 0 0;
0 2 0;
0 2 0;
0 2 0;
0 0 2;
0 0 2;
0 0 2;
];
Is there any vectorized way to perform this operation (without using for loops).
Thanks in advance;

回答(2 个)

Jordan Lui
Jordan Lui 2020-12-2
Be careful with the other answer. It will not work for more general cases. Instead, try this:
numRep = 3;
[r,c] = size(A);
B1 = repmat(A', numRep , 1);
B = reshape(B1, [], r * numRep)';

Star Strider
Star Strider 2016-1-20
This works:
A=[2 0 0;
0 2 0;
0 0 2];
[Ar,Ac] = size(A);
B1 = repmat(A, Ar, 1);
B = reshape(B1, [], size(B1,1))'
B =
2 0 0
2 0 0
2 0 0
0 2 0
0 2 0
0 2 0
0 0 2
0 0 2
0 0 2
  1 个评论
Jordan Lui
Jordan Lui 2020-12-2
This solution does not work on an example like this:
A=[2 7 8;
4 2 8;
5 6 2
-1 -1 -1;
];
Using a non square matrix and filling the off diagonals shows the issue. Result will be:
B =
2 4 5
-1 2 4
5 -1 2
4 5 -1
2 4 5
-1 7 2
6 -1 7
2 6 -1
7 2 6
-1 7 2
6 -1 8
8 2 -1
8 8 2
-1 8 8
2 -1 8
8 2 -1
The following solution works:
numRep = 3;
[r,c] = size(A);
B1 = repmat(A', numRep , 1);
B = reshape(B1, [], r * numRep)';

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by