%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 609 FALL 2011
% Simple & Rough Example for an idea of Gauss Elimination.
% Sanghyun Lee, Math Department TAMU
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

A=[ 6 -2 2 4; 12 -8 6 10 ; 3 -13 9 3 ; -6 4 1 -18 ];
B=[12 ; 34 ; 27 ; -38; ];

% Can Immediately Check the Answer.
A\B;

% For Factorization Phase ( Forward Elimination )
% This is from the Basic formula Not the Pseudocode.
for k = 1:4
    for i=1:4   
         for j=1:4 
             % for A(k)
              if i <= k
                new_A(i,j) = A(i,j);
              elseif i >= k+1 && j >= k+1
                new_A(i,j) = A(i,j) - ( A(i,k)/A(k,k) )*A(k,j) ;
              elseif i >= k+1 && j <=k
                new_A(i,j) = 0;
              end           
         end
            % for L
            if i>=k+1
                  L(i,k) =  A(i,k)/A(k,k);
            elseif i==k
                  L(i,k) = 1;
            elseif i<=k-1
                  L(i,k) = 0;
            end
            
    end
    
    A = new_A;
    
end

U=A;
L;

% Check Results.
L*U;

% for Solution Phase ( Back Substitution )
X = zeros(4,1);
for k = 1:3
    for i = k+1:4
        B(i) = B(i) - L(i,k)*B(k);
    end

    % Now X =
    for i=4:-1:1
        sum = 0;
        for j=i+1:4
            sum = sum + A(i,j)*X(j);
        end
    X(i) = ( B(i) - sum )/A(i,i);
    end

end

% Our Solution same as the result of A\B.
X

