2016-10-11 32 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 
相關問題