% -----------------------------------------------------
% curvefitting2.m
% -----------------------------------------------------
% Write a program that determines the best fit 
% polynomials of orders 1, 2 and 3 for given set of data. 
% -----------------------------------------------------
% Notes: The polyfit function uses least squares regression 
% analysis to find the best fit polynomials for curve
% fitting. 
% -----------------------------------------------------
% Copyright and license details available at matlabmarina.com
%------------------------------------------------------

clear
clc

% Given the following time and position data
t = [0,0.3,0.8,1.1,1.6,2.3]';
y = [0.5,0.92,1.14,1.25,1.25,1.40]';

% Fit a polynomial of order 1 to the data
p1 = polyfit(t,y,1);

% Use this best fit polynomial to find the position at a specific time
t_interest1 = 1.5;
y_interest1 = polyval(p1,t_interest1);

% Use this best fit polynomial to find the position at a specific range of
% time
t_interest2 = 0:0.1:3;
y_interest2 = polyval(p1,t_interest2);

% Fit a polynomial of order 2 to the data
p2 = polyfit(t,y,2);

% Use this best fit polynomial to find the position at a specific time
t_interest1 = 1.5;
y_interest3 = polyval(p2,t_interest1);

% Use this best fit polynomial to find the position at a specific range of
% time
t_interest2 = 0:0.1:3;
y_interest4 = polyval(p2,t_interest2);

% Fit a polynomial of order 3 to the data
p3 = polyfit(t,y,3);

% Use this best fit polynomial to find the position at a specific time
t_interest1 = 1.5;
y_interest5 = polyval(p3,t_interest1);

% Use this best fit polynomial to find the position at a specific range of
% time
t_interest2 = 0:0.1:3;
y_interest6 = polyval(p3,t_interest2);

y_interest_all=[y_interest1 y_interest3 y_interest5];

fprintf('The Linear function fit to the data is\n')
fprintf('y = %.3fx + %.3f\n',p1(1),p1(2))
fprintf('The value at t = %.1f is y = %.3f\n\n',t_interest1,y_interest1)

fprintf('The Quadratic function fit to the data is\n')
fprintf('y = %.3fx^2 + %.3fx + %.3f\n',p2(1),p2(2),p2(3))
fprintf('The value at t = %.1f is y = %.3f\n\n',t_interest1,y_interest3)

fprintf('The Cubic function fit to the data is\n')
fprintf('y = %.3fx^3 + %.3fx^2 + %.3fx + %.3f\n',p3(1),p3(2),p3(3),p3(4))
fprintf('The value at t = %.1f is y = %.3f\n',t_interest1,y_interest5)
