%% Curve fitting example 2

%% find acceleration: fit data with quadratic function y = c1*1 + c2*t + c3*t^2
% We assume a car is driving with constant acceleration. In order to find
% the acceleration we measure the position y at four t-values.

                         % given data:
t = [0;1;2;3];           %   t-values
y = [0;1;4;7];           %   y-values

data = [t,y]             % table of given t and y values
plot(t,y,'o')            % plot given data points
xlabel('t');ylabel('y')
grid on; xlim([-.4,3.4]); title('given data points')

A = [t.^0,t,t.^2]        % matrix A

%% Solve normal equations
% The normal equations are a 3 by 3 linear system.
%
% *Result:* The best least squares fit is y = -0.1 + 0.9*t + 0.5*t^2, so the estimated acceleration is 2*c3 = 1.

M = A'*A
g = A'*y
c = M\g

tp = (-0.4:.1:3.4)';     % t-values for plotting curve
yp = [tp.^0,tp,tp.^2]*c; % y-values for fitted curve

plot(t,y,'o',tp,yp)      % plot data points together with fitted curve
xlabel('t');ylabel('y')
grid on; title('given data points with fitted curve')

%% Check residual vector
% Find the norm of the residual vector r. Check that r is really orthogonal on the columns of the matrix A.

r = A*c - y              % residual vector
norm_r = norm(r)         % norm
A'*r                     % dot product of columns of A with r 
                         % gives zero, up to roundoff error from machine accuracy



