% Approximate the temperature distribution on 
% a unit square square, using a five-point formula. 

N = 40; h = 1/N;
tol = 1.e-3

T = 0.5*ones(N+1,N+1);
x = [0:h:1];

% Boundary conditions. 
T(1:N+1,1)=x;
T(1,1:N+1)=0.5*x';
T(1:N+1,N+1)=0.5*(1+x);
T(N+1,1:N+1)=1;
surf(T')
pause

for k=1:500
    error = 0;
    for i=2:N
        for j=2:N
            Told = T(i,j);
            T(i,j)=0.25*(T(i+1,j)+T(i-1,j)+T(i,j-1)+T(i,j+1));
            error = max(error,abs(T(i,j)-Told));
        end
    end
    surf(T'), 
    title(sprintf('k=%2d, error=%6.4e',k,error));
    pause(0.1);
   
    if error < tol 
        break;
    end
end

