2016-10-11 73 views
0

您如何在MATLAB中编写此代码? enter image description here雅可比法求解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 

回答

2

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