Repeat a matrix in Matlab

huangapple go评论76阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月27日 15:52:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定