% HW13-3
% This is a pseudocode for Jacobi iteration, not a matlab code
% This pseudocode illustrates how to perform Jacobi iteration for
% a fixed number of steps


N=100;
h=1/N;
% Input b(i,j) = f(i*h,j*h);  where f is given;
for j=1:N-1
   for i=1:N-1
      b(i,j) = f(i*h,j*h)
   end 
end 
 
% Input uo(i,j) = 0 , un(i,j)=0 ,where uo is "old" u , un is "new" u .
% Note that, this loop does not work for matlab/octave, 
% since they do not allow the index i=0 or j=0.
for j=0:N
   for i=0:N
      uo(i,j) = 0
      un(i,j) = 0
   end 
end 

% An example of 200 Jacobi iterations
% Note again that, this loop does not work for matlab/octave for the same reason.
% In matlab, you have to write i=0, j=0 separately, or shift the index
% from u(0:N,0:N) to u(1:N+1, 1:N+1)
% Also note that only u(1:N-1,1:N-1) are updated in the loop.
% The boundary values of u remain unchanged (=0)

for k=1:200               
    for j=1:N-1
        for i=1:N-1
            un(i,j) = ( uo(i-1,j)+uo(i+1,j)+uo(i,j-1)+uo(i,j+1) )/4 - h^2*b(i,j)/4
        end
    end
    
    % save values of un into uo
    for j=1:N-1
        for i=1:N-1
            uo(i,j) = un(i,j);
        end
    end
end

output un(i,j)

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

% This is another pseudocode for Jacobi iteration, not a matlab code
% This pseudocode illustrates how to perform Jacobi iteration with stopping
% criterion

% stopping criterion
kmax = 200;  % maximun number of iterations
tol = 1.0E-7;   % tolerance

% initial

N=100;
h=1/N;

% Input b(i,j) = f(i*h,j*h);  where f is given;
for j=1:N-1
   for i=1:N-1
      b(i,j) = f(i*h,j*h)
   end 
end
 
% Input uo(i,j) = 0 , un(i,j)=0 ,where uo is u "old" , un is u "new
% Note again that, this loop does not work for matlab/octave, see comments above
for j=0:N
   for i=0:N
      uo(i,j) = 0
      un(i,j) = 0
   end 
end 

% main loop
% Note again that, this loop does not work for matlab/octave, see comments above

k=0;
while ( (k < kmax) & (rmax > tol) )               
    rtmp=0;
    for j=1:N-1
        for i=1:N-1
            un(i,j) = ( (uo(i-1,j)+uo(i+1,j)+uo(i,j-1)+uo(i,j+1) )/4 - h^2*b(i,j)/4;
            rtmp = max(rtmp, abs(-4*(un(i,j)-uo(i,j))/h^2) ); % in order to find max(residual)
        end
    end
    rmax = rtmp; % found max of residual
 
    for j=1:N-1
        for i=1:N-1
            uo(i,j) = un(i,j);
        end
    end
    k=k+1;
end

output un(i,j)