Repeat a matrix in Matlab

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

Repeat a matrix in Matlab

问题

如果A是一个4x3的矩阵:

A =

  1. 0.5991 0.2336 0.0323
  2. 0.3799 0.8422 0.5569
  3. 0.8399 0.2050 0.6213
  4. 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 =

  1. 0.5991 0.2336 0.0323
  2. 0.3799 0.8422 0.5569
  3. 0.8399 0.2050 0.6213
  4. 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是列优先的,所以在重塑之前需要进行转置(.')以获得正确的元素顺序。

  1. A = [0.5991 0.2336 0.0323
  2. 0.3799 0.8422 0.5569
  3. 0.8399 0.2050 0.6213
  4. 0.1740 0.2895 0.0185];
  5. A = reshape(A.',1,size(A,2),[]); % 将其“展平”为1*3*4
  6. n = 2; % 行重复的次数
  7. A = repmat( A, n, 1, 1 ); % 复制为n*3*4

输出结果:

  1. >> A
  2. A(:,:,1) =
  3. 0.5991 0.2336 0.0323
  4. 0.5991 0.2336 0.0323
  5. A(:,:,2) =
  6. 0.3799 0.8422 0.5569
  7. 0.3799 0.8422 0.5569
  8. A(:,:,3) =
  9. 0.8399 0.2050 0.6213
  10. 0.8399 0.2050 0.6213
  11. A(:,:,4) =
  12. 0.1740 0.2895 0.0185
  13. 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.

  1. A = [0.5991 0.2336 0.0323
  2. 0.3799 0.8422 0.5569
  3. 0.8399 0.2050 0.6213
  4. 0.1740 0.2895 0.0185];
  5. A = reshape(A.',1,size(A,2),[]); % "flatten" into 1*3*4
  6. n = 2; % number of row repeats
  7. A = repmat( A, n, 1, 1 ); % replicate into n*3*4

Output:

  1. >> A
  2. A(:,:,1) =
  3. 0.5991 0.2336 0.0323
  4. 0.5991 0.2336 0.0323
  5. A(:,:,2) =
  6. 0.3799 0.8422 0.5569
  7. 0.3799 0.8422 0.5569
  8. A(:,:,3) =
  9. 0.8399 0.2050 0.6213
  10. 0.8399 0.2050 0.6213
  11. A(:,:,4) =
  12. 0.1740 0.2895 0.0185
  13. 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:

确定