function x = gs(A,b,x0)
% Function to demonstrate the Gauss-Seidel method to solve a system Ax=b
%  EDITED for No OUTPUT
% A is nxn matrix of coefficients
% b is nx1 column vector of constants
% xo is nx1 column vector of the initial guess
% x is the solution (nx1 column)
%
% Syntax: x = gs_compact(A,b,x0)

[rA,cA] = size(A);  % Determine the size of A
[rb,cb] = size(b);  % Determine the size of b

% Input checks
if rA ~= cA
    disp('Error: A is not a square matrix')
    return
else
    n = rA;
end
if cb ~= 1
    disp('Error: b is not a column vector')
    return
end
if cA ~= rb
    disp('Error: Matrix and vector dimensions are not compatible')
    return
end
dA = det(A);
if dA == 0
    disp('Error: Matrix is singular')
    return
end

% Initialize the variables
maxit = 500;
es = 1e-8;
er = 1;
x = x0;
xold = x;
count = 0;

% main loop
while(er>es && count<maxit)
    count = count + 1;          % Increment the counter
    for i = 1:n       
        x(i) = (b(i) - A(i,1:i-1)*x(1:i-1) - A(i,i+1:n)*xold(i+1:n))./A(i,i);
    end
    er = norm(x-xold)/norm(x);    % approximate relative error
    xold = x;
end

