Repmat the rows of a matrix

8 views (last 30 days)
Luis Isaac
Luis Isaac on 20 Jan 2016
Answered: Jordan Lui on 2 Dec 2020
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;

Answers (2)

Jordan Lui
Jordan Lui on 2 Dec 2020
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 on 20 Jan 2016
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 Comment
Jordan Lui
Jordan Lui on 2 Dec 2020
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)';

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!