如何将零行和列插入到Matlab Matrix中

时间:2017-12-09 12:25:32

标签: matlab matrix

我有一个3x3矩阵k1,我想将其转换为5x5矩阵,k1g。通过将零插入k1的某些行和列来创建k1g。在这种情况下,我想在第3行和第4行以及第3列和第4列中插入零,并保留k1矩阵中的现有值。下面的代码完成了我想要做的事情,但似乎这是一个很长的方法,我需要在很多问题上多次这样做。

clc
clear all
format long;
k1 = [20,50,-20;
     60,20,-20;
   -20,-20,40]
k1g = zeros(5,5);
k1g(1:2,1:2) = k1(1:2,1:2);
k1g(5:5,1:2) = k1(3:3,1:2);
k1g(1:2,5:5) = k1(1:2,3:3);
k1g(5,5) = k1(3,3)

以上是上述代码的输出:

k1 =

    20    50   -20
    60    20   -20
   -20   -20    40


k1g =

    20    50     0     0   -20
    60    20     0     0   -20
     0     0     0     0     0
     0     0     0     0     0
   -20   -20     0     0    40

有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:2)

您只需要概括您的方法。例如用:

function k1g = rowcolsof0s(k1,rowsof0s,colsof0s)
k1g = ones(size(k1)+[numel(rowsof0s) numel(colsof0s)]);  %Initialising matrix with ones
k1g(rowsof0s,:) = 0;    %Changing the elements of desired rows to zeros
k1g(:,colsof0s) = 0;    %Changing the elements of desired columns to zeros
k1g(logical(k1g)) = k1; %Transferring the contents of k1 into k1g
end

现在用:

调用该函数
rowsof0s = [3 4];       %rows where you want to insert zeros
colsof0s = [3 4];       %columns where you want to insert zeros

k1g = rowcolsof0s(k1, rowsof0s, colsof0s);