clc, clear, close all

A = [10 -1 2; 1 11 -1; 2 -1 10]
B = [6; 25; -11]

function x = g_seidel(A,B)
D = diag(diag(A));
L = tril(A,-1);
U = triu(A,1);
eps = 1e-6;
x = zeros(size(A,1),1);

m_it = 1000;

for k = 1:m_it
    x_old = x;

    for i = 1:size(A,1)
        x(i) = (B(i)- L(i, 1:i-1) * x(1:i-1) - U(i,i+1:end) * x(i+1:end))/D(i,i);
    end

    if norm(x - x_old, inf) < eps
        fprintf("Gauss Seidel Converged in %d iterations\n", k);
        break;
    end
end
end

function x = jacobi(A,B)
D = diag(diag(A));
L = tril(A,-1);
U = triu(A,1);
eps = 1e-6;

x = zeros(size(A,1),1);

m_it = 1000;

for k = 1:m_it

    x_new = D \ (B - (L + U) * x);

    if norm(x - x_new, inf) < eps
        fprintf("Jacobi Converged in %d iterations\n", k);
        break;
    end

    x = x_new;
end

end

fprintf("Inbuilt MATLAB solver\n")
x = A\B

x = jacobi(A,B)

x = g_seidel(A,B)