%----------------------------------------------------------------
%     
%     A program that uses the conjugate gradient method (cgm).
%     to solve:
%                     [A]{x} - {f}  =  0
%     
%----------------------------------------------------------------
       clear

%----------------------------------------------------------------
%    Create equations:
%----------------------------------------------------------------
     neq = 500; 
     choice = 2;     % Symmetric matrix ordered entries
     choice = 3;     % Symmetric banded and ordered entries
     choice = 1;     % Symmetric matrix with random entries

     if choice == 1
       for i=1:neq;
          x(i,1) = 0;
          y(i,1) = rand(1);
          for j=1:neq;
	    if j>i
	       A(i,j) = -rand(1);
            elseif j == i;
	       A(i,i) = neq*rand(1);
            else
	       A(i,j) = A(j,i);
            end
          end
       end
       f = A*y;

     elseif choice == 2
       d = (neq*neq-neq)/2 + neq;
       for i=1:neq;
          x(i,1) = 0;
          y(i,1) = rand(1);
          for j=1:neq;
	    if j>i
	       A(i,j) = -j;
            elseif j == i;
	       A(i,i) = d;
            else
	       A(i,j) = -i;
            end
          end
       end
       f = A*y;
     elseif choice == 3
       IB = 20;
       d = 2.0*IB;
       for i=1:neq;
          x(i,1) = 0;
          y(i,1) = rand(1);
          for j=1:neq;
	    if i-j>IB | j-i>IB
	      A(i,j) = 0.0;
            else
	      A(i,j) = -1.0;
            end
	    if i == j
	      A(i,i) = d;
            end
          end
       end
       f = A*y;
     end
%----------------------------------------------------------------

%    Condition equations 
     [A,x,f] = cond(A,x,f,neq,1);

%    Solve using Conjugant Gradient method
     x = CG(A,x,f,neq);

%    unCondition answer 
     [A,x,f] = cond(A,x,f,neq,2);

%----------------------------------------------------------------

