% HW13-3
% This is a pseudocode for SOR iteration, not a matlab code
% This pseudocode illustrates how to perform SOR iteration for
% a fixed number of steps
% See the second part of G-S.txt on how to add stopping criterion

N=100;
h=1/N;
w=0.5  % A randomly chosen SOR parameter. See hw 11 problem 3(d) for the best w

% 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 u(i,j) = 0;
% 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
      u(i,j) = 0
   end 
end 

% An example of 200 SOR 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
            uGS = ( u(i-1,j)+u(i+1,j)+u(i,j-1)+u(i,j+1) )/4 - h^2*b(i,j)/4
            u(i,j) = u(i,j) + w*( uGS - u(i,j) )
        end
    end
end

output u(i,j)

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


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

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 u(i,j) = 0;
% Note again that, this loop does not work for matlab/octave, see comments above
for j=0:N
   for i=0:N
      u(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
            uGS = ( u(i-1,j)+u(i+1,j)+u(i,j-1)+u(i,j+1) )/4 - h^2*b(i,j)/4;
            utmp = u(i,j) + w*( uGS - u(i,j) );
            rtmp = max(rtmp, abs(-4*(utmp-u(i,j))/h^2) );  % in order to find max(residual)
            u(i,j) = utmp;
        end
    end
    rmax = rtmp;  % found max of residual
    k=k+1;
end

output u(i,j)
