%% Heat equation u_t=u_xx - explicit finite difference scheme

% Probably the simplest implementation of the (explicit) finite difference 
% scheme for the heat equation u_t=u_xx on the interval 0<x<1 with boundary
% conditions u(0,t)=0, u(1,t)=0 and initial condition as given in (2.24)

% Copyleft 2010 Radu C. Cascaval, UCCS

%%
% time step and spatial step size
dt = 0.0013;
dx = 0.05;

% number of time iterations
N = 50; 

% final time of the computation
Tf = N*dt; 

% the mesh ratio
mu = dt/dx^2;  

tvals = 0:dt:Tf;
xvals = 0:dx:1;

N=length(tvals);
J=length(xvals);

u0 = @(x) 1-2*(x-1/2).*sign(x-1/2);

u = zeros(J,N);
u(:,1) = u0(xvals);

for n = 1:N-1
	u(2:J-1,n+1) = mu*u(3:J,n) + (1-2*mu)*u(2:J-1,n)+mu*u(1:J-2,n);
	u(1,n+1) = 0;
	u(J,n+1) = 0;
end

surf(xvals, tvals, u')
xlabel x; ylabel t; zlabel u  
title(strcat('mesh size dx',num2str(dx),...
    ', ratio mu=dt/(dx)^2= ',num2str(mu)))
