代码之家  ›  专栏  ›  技术社区  ›  JuMoGar

如何在RHS上用二维矩阵求解线性方程组

  •  1
  • JuMoGar  · 技术社区  · 7 年前

    我正在努力解决这个问题:

    Problem to solve

    我试图为右侧(RHS)声明一个矩阵矩阵,但我不知道如何实现。我正在尝试:

    MatrizResultados = [[1, 3; -1, 2]; [0, 4; 1, -1]; [2, 1; -1, 1]]
    

    但结果都是一个矩阵,如下所示:

    MatrizResultados =
    
     1     3
    -1     2
     0     4
     1    -1
     2     1
    -1     1
    

    如何在一个矩阵中存储这些单独的矩阵来解决上述问题?

    以下是我当前的Matlab代码,用于尝试解决此问题:

    syms X Y Z;
    
    MatrizCoeficientes = [-1, 1, 2; -1, 2, 3; 1, 4, 2];
    MatrizVariables = [X; Y; Z];
    MatrizResultados = [[1, 3; -1, 2]; [0, 4; 1, -1]; [2, 1; -1, 1]];
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Wolfie Radu Stefan    7 年前

    符号数学工具箱在这方面做得太过火了。

    这是4个独立的方程组,因为加法是线性的,即矩阵元素中没有交叉。例如,你有

    - x(1,1) + y(1,1) + 2*z(1,1) = 1
    - x(1,1) + 2*y(1,1) + 3*z(1,1) = 0
      x(1,1) + 4*y(1,1) + 2*z(1,1) = 2
    

    可以使用 mldivide ( \ )运算符,来自系数矩阵。可以这样构造:

    % Coefficients of all 4 systems
    coefs = [-1 1 2; -1 2 3; 1 4 2];
    % RHS of the equation, stored with each eqn in a row, each element in a column
    solns = [ [1; 0; 2], [-1; 1; -1], [3; 4; 1], [2; -1; 1] ];
    
    % set up output array
    xyz = zeros(3, 4);
    % Loop through solving the system
    for ii = 1:4
        % Use mldivide (\) to get solution to system
        xyz(:,ii) = coefs\solns(:,ii);
    end
    

    结果:

    % xyz is a 3x4 matrix, rows are [x;y;z], 
    % columns correspond to elements of RHS matrices as detailed below
    xyz(:,1) % >> [-10   7  -8], solution for position (1,1)
    xyz(:,2) % >> [ 15 -10  12], solution for position (2,1)
    xyz(:,3) % >> [ -1   0   1], solution for position (1,2)
    xyz(:,4) % >> [-23  15 -18], solution for position (2,2)