【问题标题】:Jacobi method to solve linear systems in MATLAB在 MATLAB 中求解线性系统的 Jacobi 方法
【发布时间】:2016-10-11 04:19:04
【问题描述】:

您将如何在 MATLAB 中编写代码?

这是我尝试过的,但效果不太好。

function x = my_jacobi(A,b, tot_it)
%Inputs:
%A: Matrix
%b: Vector
%tot_it: Number of iterations
%Output:
%:x The solution after tot_it iterations
    n = length(A);
    x = zeros(n,1);
    for k = 1:tot_it
      for j = 1:n
        for i = 1:n
            if (j ~= i) 
                x(i) = -((A(i,j)/A(i,i)) * x(j) + (b(i)/A(i,i)));

            else
                continue;
            end
          end
      end
  end
end

【问题讨论】:

    标签: matlab iteration linear-algebra


    【解决方案1】:

    j 是对每个 i 求和的迭代器,因此您需要更改它们的顺序。此外,该公式有一个总和,并且在您的代码中您没有添加任何内容,因此这是另一件需要考虑的事情。我看到您忽略的最后一件事是您应该保存 x 的先前状态,因为公式的右侧需要它。你应该尝试这样的事情:

    function x = my_jacobi(A,b, tot_it)
      %Inputs:
      %A: Matrix
      %b: Vector
      %tot_it: Number of iterations
      %Output:
      %:x The solution after tot_it iterations
      n = length(A);
      x = zeros(n,1);
      s = 0; %Auxiliar var to store the sum.
      xold = x
      for k = 1:tot_it
        for i = 1:n
          for j = 1:n
            if (j ~= i) 
              s = s + (A(i,j)/A(i,i)) * xold(j);
            else
              continue;
            end
          end
          x(i) = -s + b(i)/A(i,i);
          s = 0;
        end
        xold = x;
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多