% [u,err,x,t] = heat_eul_dir(t_0,t_f,M,N)
%
% solves the heat equation u_t = D u_xx on [0,L] with initial data u_0 =
% sin(k pi x/L) with dirichlet conditions using finite-differences in
% space and explicit time-stepping.  t_0 is the initial time, t_f is the
% final time, N is the number of intervals in space, and M is the number of
% intervals in time.  err is the error. 

function [u,err,x,t] = heat_eul_dir(t_0,t_f,M,N)

% define the length of the interval
L = 2*pi;
% define the mesh in space
dx = L/N;
% there are N subintervals and N+1 meshpoints.  Labelled x_1 to x_{N+1}
% because matlab doesn't allow 0 as an index
x = 0:dx:L;
x = x';

% define the mesh in time
dt = (t_f-t_0)/M
t = t_0:dt:t_f;

% define the diffusivity
D = 2;
% define the ratio r.  This is lambda in the class notes.  We need
% r < 1/2 for stability
display('the following should be less than 1/2')
r = D*dt/dx^2

% choose the wave number of the initial data and give its decay rate
k = 4;
sigma = D*(k*pi/L)^2;
% define the initial data:
u(:,1) = sin(k*pi*x/L);
err(:,1) = u(:,1) - exp(-sigma*(t(1)-t_0))*sin(k*pi*x/L);

% for internal points, have
%    u_new(j) = u_old(j) + r*(u_old(j+1)-2*u_old(j)+u_old(j-1))
% for the two endpoints, the homogeneous Dirichlet BCs imply
%    u_new(1) = 0
%    u_new(N+1) = 0

for j=1:M
  u(1,j+1) = 0;
  for i=2:N
    u(i,j+1) = u(i,j) + r*(u(i+1,j)-2*u(i,j)+u(i-1,j));
  end
  u(N+1,j+1) = 0;
  err(:,j+1) = u(:,j+1) - exp(-sigma*(t(j+1)-t_0))*sin(k*pi*x/L);
end

