%GAUSS-SEIDEL ITERATION
%(Selcuk Bayin, METU-NCC, bayin@metu.edu.tr)
%EXAMPLE FROM KREYSZIG 
clc
A=[2 1 1;1 2 1;1 1 2]
b=[4 4 4]
%%
%bb is b-tilde
bb=b;
bb(1,1)=bb(1,1)/A(1,1);
bb(1,2)=bb(1,2)/A(2,2);
bb(1,3)=bb(1,3)/A(3,3);
bb
n=3;
L=zeros(n);
%%
clc
L(2,1)=A(2,1)/A(2,2);
L(3,1)=A(3,1)/A(3,3);
L(3,2)=A(3,2)/A(3,3)
%%
U=zeros(n);
U(1,2)=A(1,2)/A(1,1);
U(1,3)=A(1,3)/A(1,1);
U(2,3)=A(2,3)/A(2,2)
%%
E=eye(n);
C=(E+L);
CINV=inv(C)
%%
%PICK a TRIAL SOLUTION
clc
x=[2 1 2]
xnew=x'
%%
%ITERATE ONCE
clc
xnew=CINV*(bb'-U*xnew)
r=A*xnew-b'
rr=(r(1)^2+r(2)^2+r(3)^2)^(1/2)
%CONTINUE ITERATING
%%
while rr>0.001
    xnew=CINV*(bb'-U*xnew);
    r=A*xnew-b';  
    rr=(r(1)^2+r(2)^2+r(3)^2)^(1/2);
end
xnew
rr
%%
%CHECK WITH THE RREF COMMAND
%WRITE THE AUGMENTED MATRIX
clc
AUGM=[2 1 1 4;1 2 1 4;1 1 2 4]
%%
%EXECUTE RREF
RREF=rref(AUGM)
%%
%COMPARE THE EXACT AND THE APPROX. SOLNS.
EXAXTsoln=RREF(:,4)
APPROXsoln=xnew
ERROR=rr
