英文:
Repeat a matrix in Matlab
问题
如果A是一个4x3的矩阵:
A =
0.5991 0.2336 0.0323
0.3799 0.8422 0.5569
0.8399 0.2050 0.6213
0.1740 0.2895 0.0185
如何重复每一行n次,使得A成为一个3D矩阵,即第三个维度为4,如下所示:
A_new =
A(:,:,1) =
0.5991 0.2336 0.0323
0.5991 0.2336 0.0323
A(:,:,2) =
0.3799 0.8422 0.5569
0.3799 0.8422 0.5569
A(:,:,3) =
0.8399 0.2050 0.6213
0.8399 0.2050 0.6213
A(:,:,4) =
0.1740 0.2895 0.0185
0.1740 0.2895 0.0185
期望得到一个3D矩阵。
英文:
IF A is 4*3 matrix:
A =
0.5991 0.2336 0.0323
0.3799 0.8422 0.5569
0.8399 0.2050 0.6213
0.1740 0.2895 0.0185
How to repeat each row n time such that A to be a 3D matrix i.e, the third dimension is 4 as it is to be like this
A_new =
A(:,:,1) =
0.5991 0.2336 0.0323
0.5991 0.2336 0.0323
A(:,:,2) =
0.3799 0.8422 0.5569
0.3799 0.8422 0.5569
A(:,:,3) =
0.8399 0.2050 0.6213
0.8399 0.2050 0.6213
A(:,:,4) =
0.1740 0.2895 0.0185
0.1740 0.2895 0.0185
expecting a 3d matrix
答案1
得分: 3
你可以将A重塑为一个1*3*4
的矩阵,然后根据需要重复多行,例如你的例子中是两行。
需要注意的是,MATLAB是列优先的,所以在重塑之前需要进行转置(.'
)以获得正确的元素顺序。
A = [0.5991 0.2336 0.0323
0.3799 0.8422 0.5569
0.8399 0.2050 0.6213
0.1740 0.2895 0.0185];
A = reshape(A.',1,size(A,2),[]); % 将其“展平”为1*3*4
n = 2; % 行重复的次数
A = repmat( A, n, 1, 1 ); % 复制为n*3*4
输出结果:
>> A
A(:,:,1) =
0.5991 0.2336 0.0323
0.5991 0.2336 0.0323
A(:,:,2) =
0.3799 0.8422 0.5569
0.3799 0.8422 0.5569
A(:,:,3) =
0.8399 0.2050 0.6213
0.8399 0.2050 0.6213
A(:,:,4) =
0.1740 0.2895 0.0185
0.1740 0.2895 0.0185
英文:
You can reshape
A to be a 1*3*4
matrix, then simply repeat for as many rows as you want - two in your example.
Be wary because MATLAB is column-major, you have to do a transpose (.'
) before the reshape to get the correct element ordering.
A = [0.5991 0.2336 0.0323
0.3799 0.8422 0.5569
0.8399 0.2050 0.6213
0.1740 0.2895 0.0185];
A = reshape(A.',1,size(A,2),[]); % "flatten" into 1*3*4
n = 2; % number of row repeats
A = repmat( A, n, 1, 1 ); % replicate into n*3*4
Output:
>> A
A(:,:,1) =
0.5991 0.2336 0.0323
0.5991 0.2336 0.0323
A(:,:,2) =
0.3799 0.8422 0.5569
0.3799 0.8422 0.5569
A(:,:,3) =
0.8399 0.2050 0.6213
0.8399 0.2050 0.6213
A(:,:,4) =
0.1740 0.2895 0.0185
0.1740 0.2895 0.0185
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论