% CLASS2DEC   Do composite trapezoid and composite Simpson's rule on an example where
%   we know the exact integral:
%                /2   -x             -2
%                |   e   dx  =  1 - e
%                /1
% Notes: 
%   1. In this case, composite Simpsons with 16 subintervals does
%      just as well as composite trapezoid with 500 subintervals
%   2. Simpson's is apparently a lot better ... and that's true in
%      pretty-good generality for smooth functions.

f = @(x) exp(-x);

% report exact answer
exact = 1 - exp(-2)

% trapezoid rule approximations:
n=17;    h = (2-0)/n;  xi = 0:h:2;  trap17   = h * sum([0.5 ones(1,n-1) 0.5] .* f(xi))
err=abs(trap17-exact)
n=500;   h = (2-0)/n;  xi = 0:h:2;  trap500  = h * sum([0.5 ones(1,n-1) 0.5] .* f(xi))
err=abs(trap500-exact)
n=10000; h = (2-0)/n;  xi = 0:h:2; trap10000 = h * sum([0.5 ones(1,n-1) 0.5] .* f(xi))
err=abs(trap10000-exact)

% simpson's rule approximations
n=4;     h = (2-0)/n;  xi = 0:h:2;   simp4 = (h/3) * sum([1 repmat([4 2],1,(n/2)-1) 4  1] .* f(xi))
err=abs(simp4-exact)
n=16;    h = (2-0)/n;  xi = 0:h:2;  simp16 = (h/3) * sum([1 repmat([4 2],1,(n/2)-1) 4  1] .* f(xi))
err=abs(simp16-exact)
n=500;   h = (2-0)/n;  xi = 0:h:2; simp500 = (h/3) * sum([1 repmat([4 2],1,(n/2)-1) 4  1] .* f(xi))
err=abs(simp500-exact)

% just show how to build pattern of coefficients in Simpson's
n=16;   
repmat_result    = repmat([4 2],1,(n/2)-1)
simpsons_pattern = [1 repmat_result 4  1]

