Jacobi方法在MATLAB中求解线性系统

时间:2016-10-11 04:19:04

标签: matlab iteration linear-algebra

您如何在MATLAB中编写代码? enter image description here

这是我尝试过的,但它不能正常工作。

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

1 个答案:

答案 0 :(得分:3)

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