%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Gauss Seidel Iteration (Version 1.0)                           %
%                                                                %
% Programmed By: MatlabSite.com Programmers Team                 %
%  
% Reproduced by: www.Chemical-Eng.blog.ir
%                                                                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clc;
clear;
disp('Gauss Seidel Iteration (Version 1.0)');
disp(' ');
disp('Programmed By: MatlabSite.com Programmers Team, 2009');
disp(' ');

A=[   -10     4     2     1
        1    12    -4     2
        3    -2     8     1
        5     1    -2    13   ];

b=[    80   210   270   530   ]';    

n=numel(b);

disp('This program solves the Linear Equations System using Gauss-Seidel method.');
disp('The system is in the form of Ax=b, where');
disp(' ');
disp('A =');
disp(A);
disp('b =');
disp(b);

maxiter=1000;
iter=0;

xold=zeros(n,1);
xnew=zeros(n,1);
e=inf;
mine=0.00001;

while iter<maxiter && e>mine
    iter=iter+1;
    disp(['Iteration ' mat2str(iter) ': x = ' mat2str(xold',4)]);
    disp(' ');
    
    for i=1:n
        s=0;
        for j=1:i-1
            s=s+A(i,j)*xnew(j);
        end
        for j=i+1:n
            s=s+A(i,j)*xold(j);
        end
        xnew(i)=(b(i)-s)/A(i,i);
    end
    
    e=norm(xnew-xold);
    xold=xnew;
end
disp('Final solution is:');
disp(xnew');
