clear
echo on
format compact
%This program shows how you can use Matlab
%to do a simple error calculation.  The example
%is determining the acceleration due to gravity
%by measuring the height of a ball as a function
%of time which is initially thrown upward with 
%some velocity.  Thus:
pause
%First we set up the array of times:
t=[0:.125:2.5]';
%Note that we were careful to make this
%a column vector!

%Next we generate some artificial 'data'
%with random noise:
b=(-0.5*t.^2+1.25*t)*9.8+randn(size(t));

%and create the matrix of modelling functions:
a=[ones(size(t)),t,t.^2];
pause
%And this is the matrix k used in the solution:
k=inv(a'*a)*a';

%Here are the best fit modelling parameters:
x=k*b
pause
%Now we estimate the variance in b:
[n m]=size(a);
varb=norm(a*x-b)^2/(n-m);

%This yields the standard deviation in b:
stddev=varb^.5
%which is close to the expected value of unity
%for the randn routine.
pause
%We use the variance in b to calculate the variance
%in x:
varx=varb*k*k'
pause
%We want to generate a smooth curve for our
%best fit curve:
tp=[0:.1:2.5]';
ap=[ones(size(tp)),tp,tp.^2];
bp=ap*k*b;

%And we plot this up with the data:
plot(t,b,'o',tp,bp)
xlabel('time (sec)')
ylabel('height (m)')
drawnow
hold on
pause
%Now we calculate the variance in the model
%predictions:
varbp=varb*ap*k*k'*ap';

%And we extract the square root of the diagonal
%to get the standard deviation:
sigbp=diag(varbp).^.5;

%We add the 95% confidence interval to the plot:
plot(tp,bp+2*sigbp,'w--',tp,bp-2*sigbp,'w--')
hold off
pause
%And we finish by outputting the best fit parameter
%values and their standard deviations:
[x,diag(varx).^.5]

%The first coefficient is just half the acceleration
%due to gravity, thus the estimated gravitational
%acceleration, with random error is:
gravity = [-x(3),varx(3,3)^.5]*2

%which is reasonably close to the expected value of
%9.8 m/s^2.