Repmat the rows of a matrix
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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;
0 Kommentare
Antworten (2)
Jordan Lui
am 2 Dez. 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)';
0 Kommentare
Star Strider
am 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 Kommentar
Jordan Lui
am 2 Dez. 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)';
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!