% Second order Finite Difference approximation of problem A2 from 
% the lecture series, "Survey of Applied Mathematics Techniques",
% given at SUSTech in the Summer of 2018
%
% Written by Brian Wetton, wetton@math.ubc.ca, June 21, 2018

a=1; % parameter in the equations, taken to be one in the notes 

% Number of spatial grid points 
N=20;

% Changed to the interval [0, 2 pi] from the notes 
h = 2*pi/N;
x= (1:N)*h;

% right hand side and exact solution at grid points.
f = (a-sin(x).^2+cos(x)).*exp(cos(x));
ue = exp(cos(x));

% Set up matrix
% Could do it with a for loop instead of these fancy commands to 
%    input a sparse matrix with mostly entries near the diagonal. 
e = ones(N,1);
A = spdiags([-e/h^2 (2/h^2+a)*e -e/h^2], -1:1, N, N);

% periodic entries
A(1,N) = -1/h^2;
A(N,1) = -1/h^2;

% Solve 
U = A\f';

% Find the errors 
maxerr = max(abs(U-ue'));

fprintf('Error with N=%d is %10.8f \n',N, maxerr)

figure(1)
plot(x,U,x,ue,':')
xlabel('x')
title('Computed solution (straight line) and exact (dotted)')

figure(2)
hold on 
plot(x,U-ue')
xlabel('x')
title('Pointwise error')

hold off
