echo on
%%%%% ch02_exa3.m %%%%%
% Run script and study the effects of each line.

echo off
format compact;
format short;
disp(sprintf('**** Examples from Chapter 02 ****'));
disp(sprintf('**** Implementation of LU decomposition and backward substitution. *'));
echo on;
% Implement Gaussian elimination using triple nested loop for a system of dimension n.
n=3;
A=rand(n,n)
A= A+n.*eye(n) %create diagonaly dominant matrix
b=rand(n,1)
% The matrix U and L are not generated explicitly. The transformed matrix (upper triangular)
% is saved in the upper triangle of the original matrix A, the transformed right-hand vector
% is saved on the place of the original right-hand vector b.
echo off;
bg=b;		% Make a copy of b and A
Ag=A;
for k=1:n-1
   for i=(k+1):n
      Ag(i,k)=Ag(i,k)/Ag(k,k);
      for j=(k+1):n
         Ag(i,j)=Ag(i,j)-Ag(i,k)*Ag(k,j);
      end
      bg(i)=bg(i)-Ag(i,k)*bg(k);
   end
end
echo on;
[L U P] = lu(A)
Ag	    % Compare upper triangle of Ag with U.
bg
inv(L)*b	% inv(L)=M. Compare with bg.


% Implement backward substitution 
echo off;
xb=zeros(n,1);		% Initialize the solution vector
xb(n)=bg(n)/Ag(n,n);	%First value
for i=(n-1):-1:1 
   for j=(i+1):n
      xb(i)= xb(i) + Ag(i,j)*xb(j);
   end
   xb(i) = (bg(i)-xb(i))/Ag(i,i);
end
echo on
xb		% The solution vector after backward substitution 
xm=A\b	% The solution of the complete system should be the same as obtained by MatLab
