%==============================================================
%             |  Author: James C. Sutherland  |
%             |            CHEN 1703          |
%             |-------------------------------|
%
% This script performs regression on data to determine
% the gravitational acceleration on earth.
%
%==============================================================
 

clear; clc; close all;

% times measured
t = [ 0 0.49 0.63 0.83 0.88 0.95 ...
      0 0.47 0.67 0.79 0.94 1.0];
% height measured
h = [ 10 9 8 7 6 5 ...
      10 9 8 7 6 5 ];

% define the initial height. 
% Here we assume that it is known exactly.
h0 = h(1);

% define the matrix and RHS for the equations we will solve.
% See the class notes for more information
A = [(t'.^2)/2];
b = h'-h0;

% define and solve the normal equations
AA = A'*A;
bb = A'*b;
g=AA\bb;

% output the gravitational constant.
fprintf('g = %1.2f m/s^2\n',g);

% generate a bunch of predicted height points
% as a function of time for plotting...
t2 = linspace(0,1.0);
hpred = h0 + 0.5*g*t2.^2;

% plot the results.
plot(t,h,'ko',t2,hpred,'r-');
legend('data','best fit');
xlabel('time (s)'); ylabel('h (m)');
text(0.3,7,strcat('g=',num2str(g)));

% calculate the R2 value
hpred = h0 + 0.5*g*t.^2;
R2 = 1-sum( (h-hpred).^2 )/sum((h-mean(h)).^2);
fprintf('R2=%.4f\n',R2);
% put the R2 value on the plot.
text(0.3,6.5,strcat('R2 = ',num2str(R2)))
