Repmat the rows of a matrix
8 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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)';
0 件のコメント
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
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 Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!