Matlab - 使用空格从较小的矩阵中创建一个更大的矩阵

时间:2018-01-20 17:15:32

标签: matlab matrix

我们说我有一个3 x 3矩阵(A),我想把它变成5 x 5矩阵(B),但矩阵A有以下内容:

1 2 3
4 5 6
7 8 9

由此产生的更大的矩阵B需要具有以下内容:

1 0 2 0 3
0 0 0 0 0
4 0 5 0 6
0 0 0 0 0
7 0 8 0 9

我知道这可以通过一些" Fors"遵循如下序列:

  %% We get the dimensions of our matrix. 
  [xLength, yLength] = size(InMat); 

  %% We create a matrix of the double size.
  NewInMat = zeros(xLength * 2, yLength * 2);

  %% We prepare the counters to fill the new matrix.
  XLenN = (xLength * 2) -1;
  YLenN = (yLength * 2) - 1;

  for i = 1 : XLenN
      for j = 1 : YLenN
         if mod(i, 2) ~= 0
           if mod(j, 2) ~= 0
              NewInMat(i, j) = InMat(i, j);
           else
              NewInMat(i,j) = mean([InMat(i, j - 1), InMat(i, j + 2)]);  
           end
         end
    end
end

但我想知道是否有更简单的方法,或者Matlab是否有工具来完成这项任务。非常感谢提前!

1 个答案:

答案 0 :(得分:5)

您可以使用索引:

InMat = [...
1 2 3
4 5 6
7 8 9];
s = size(InMat)*2-1;
NewInMat(1:2:s(1), 1:2:s(2)) = InMat;

此处NewInMat同时分配和填充。

相关问题