a=1;
N=10;
% 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;
% full(A)
U = A\f';
maxerr = max(abs(U-ue'));
fprintf('Error with N=%d is %10.8f \n',N, maxerr)