function linanal(ns)
% Homogeneous PDE: Linear (1-D) Diffusion
% Analytical solutions on bounded and infinite domain
% BENG 221 example, 10/8/2013
%
% ns: number of terms in the infinite series
%
% e.g.:
% >> linanal(30);
%

% diffusion constant
global D
D = 0.001; 

% domain
dx = 0.02; % step size in x dimension
dt = 0.1;  % step size in t dimension
xmesh = -1:dx:1; % domain in x; L/2 = 1
tmesh = 0:dt:10;  % domain in t
nx = length(xmesh); % number of points in x dimension
nt = length(tmesh); % number of points in t dimension


% solution on bounded domain using separation of variables
sol_sep = zeros(nt, nx);
for n = 0:ns-1
    k = (2*n+1)*pi/2; % L = 2
    sol_sep = sol_sep + exp(-D*(k^2)*tmesh)' * cos(k*xmesh);
end

figure(1)
surf(tmesh,xmesh,sol_sep')
title(['Separation of variables on bounded domain (first ', num2str(ns), ' terms in series)'])
xlabel('t')
ylabel('x')
zlabel('u(x,t)')


% solution on infinite domain using Fourier
sol_inf = (4*pi*D*tmesh' * ones(1,nx)).^(-.5) .* exp(-(4*D*tmesh).^(-1)' * xmesh.^2);

figure(2)
surf(tmesh,xmesh,sol_inf')
title('Gaussian solution on infinite domain')
xlabel('t')
ylabel('x')
zlabel('u(x,t)')
