% jacobi2.m - MATLAB script file for Lab 09
% 
% MATLAB script that executes iterations of Jacobi's Method to solve Ax=b.
% The matrix A and vector b are assumed to already be assigned values in the
% MATLAB session. The iterates are stored in the matrix X.
%
% Written by Douglas Meade
% Created 19 September 2005
% Revised 27 September 2005

clear X
tol = 1e-8;
maxiter = 100;

relerr = inf;
niter = 1;

% Matrix A for Section 001:
%A = 9*eye(200,200) +  diag( [ones(1,100) zeros(1,99)], 1 ) +  diag( [zeros(1,99) ones(1,100)], -1 ) -2*diag( ones(1,100), 100 ) -2*diag( -2*ones(1,100), -100 )
% Matrix A for Section 002:
%A = 9*eye(200,200) -2*diag( [ones(1,100) zeros(1,99)], 1 ) -2*diag( [zeros(1,99) ones(1,100)], -1 ) +  diag( ones(1,100), 100 ) +  diag( -2*ones(1,100), -100 )

%S = diag( diag(A) );
%T = S - A;
X(:,1) = zeros(200,1);

while relerr >= tol & niter < maxiter,
%   X(:,niter+1)=S \ (b+T*X(:,niter));
   
% Section 001
   for k=1:100,
      X(k,niter+1) = (k-X(k+1,niter)+2*X(k+100,niter))/9;
   end
   for k=101:200,
      X(k,niter+1) = (k-X(k-1,niter)+2*X(k-100,niter))/9;
   end
   
%% Section 002
%   for k=1:100,
%      X(k,niter+1) = (k+2*X(k+1,niter)-X(k+100,niter))/9;
%   end
%   for k=101:200,
%      X(k,niter+1) = (k+2*X(k-1,niter)-X(k-100,niter))/9;
%   end
   
   relerr = norm( X(:,niter)-X(:,niter+1),inf )/norm( X(:,niter+1),inf );
   niter = niter+1;
end

%disp( 'Results of Jacobi''s Method' )
%disp( '---------------------------' )
%disp( '' )
fprintf( '\n\nAfter %g iterations of Jacobi''s Method the relative error is %g.\n', niter, relerr )