%% Fitting a Line to a Scatter Plot from Given Data
%% Data Provided
% Below is the data given for this assignment.
% x vector below shows the age of child in months.
% y vector below shows the child's height in inches
x = [0; 1; 2; 3; 4; 5; 6; 7];
y = [19.75; 21.4; 23.5; 23.1; 23.8; 25; 26.4; 27.25]; 

%% Plotting the Data: Age and Height of Child
figure(1)
scatter(x, y, 'b');
grid on
%hold on
title('Height of Child vs Age');
xlabel('Age of Child (months)');
ylabel('Height of a Child (inches)');

%% Obtaining Weights for the Best Fit Line Using Linear Regression
X_fit = [1 0; 1 1; 1 2; 1 3; 1 4; 1 5; 1 6; 1 7]; % X values for linear
                                                 % fit plot line
                                                 
X_Tpose = transpose(X_fit); % transpose of X_fit vector
X_cross = ((X_Tpose*X_fit)^-1)*X_Tpose; % inverse of X_fit 
w = X_cross*y; % w parameters to be used on function fit line
disp('The weights given by the algorithm to produce a best fit line for the data are below');
disp(w);


%% Plotting the Data and the Best Fit Line 
figure(2)
scatter(x, y, 'b');
grid on
hold on
title('Height of Child vs Age');
xlabel('Age of Child (months)');
ylabel('Height of a Child (inches)');

fprintf('y-intercetp is %g and slope is %g\n',round(w(1),4),round(w(2),4));
fprintf('y = %gx + %g\n',round(w(2),4),round(w(1),4));
% creating a fit line to plot againts the data plot to show this is 
% the best fit line.
% the weights, (w's), used to produced this plot are the w's generated
% by the algorithm above.
x_fit_plot = (0:7);   
y_fit = w(2,1)*x_fit_plot + w(1,1); % funciton line used for fit
plot(x_fit_plot, y_fit, 'm')
legend('height vs age', 'line fit function', 'location','northwest')
text(3,21,'best fit line','FontSize',12);
txt = ['y = 0.9845x + 20.3292'];
text(3,20.5,txt,'FontSize',12);
hold off
