
clc, clear

%% 初始化
  A = [2 -1 0; -1 3 -1; 0 -1 2];
  b = [1;8;-5];
tol = 1e-5;
x(:,1) = zeros(size(A,1),1);
xm(:,1) = zeros(size(A,1),1);

B = A;
B(eye(size(A,1),'logical')) = 0; % 对角线元素赋值为0

%% Jacobi 迭代
n = 1;
while norm(b - A*x(:,n)) >= tol
    
    x(:,n+1) = ( b - B*x(:,n) )./diag(A);
    n = n+1;
    
end

fprintf('\n Jacobi迭代：%d 步，x = [%g,%g,%g]\n\n',n-1,x(1,end),x(2,end),x(3,end));

%% Jacobi 迭代改进
n = 1;
while norm(b - A*xm(:,n)) >= tol
    
    xx = xm(:,n);
    for k = 1: size(A,1)
        xm(k,n+1) = ( b(k) - B(k,:)*xx )./A(k,k);    
        xx(k) = xm(k,n+1); % 更新 x_i^k 为 x_i^{k+1}
    end
    n = n+1;
    
end

fprintf('\n Jacobi改进迭代：%d 步，x = [%g,%g,%g]\n\n',n-1,xm(1,end),xm(2,end),xm(3,end));

