
clc, clear

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

L = tril(A,-1);
U = triu(A,0);

%% SOR 迭代
n = 1;
while norm(b - A*x(:,n)) >= tol
    
    xx = x(:,n);
    for k = 1: size(A,1)
        x(k,n+1) = x(k,n) + omega*( b(k) - L(k,1:k-1)*xx(1:k-1) - U(k,k:end)*x(k:end,n) )./A(k,k);    
        xx(k) = x(k,n+1); % 更新 x_i^k 为 x_i^{k+1}
    end
    n = n+1;
    
end

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