%% Model Data with Polynomial
%% Section 1
% This example shows how to model data with a polynomial.
% Measure a quantity y at several values of time t.

t = [0 0.3 0.8 1.1 1.6 2.3];
y = [0.6 0.67 1.01 1.35 1.47 1.25];
plot(t,y,'o')
title('Plot of y Versus t')

% You can try modeling this data using a second-degree polynomial function,
% y=a_{2}t^{2} + a_{1}t + a_{0}.
% The unknown coefficients, a_{0}, a_{1}, and a_{2}, are computed by minimizing the sum of the squares of the deviations of the data from the model (least-squares fit).
%
% Use polyfit to find the polynomial coefficients.

p = polyfit(t,y,2)

% MATLAB calculates the polynomial coefficients in descending powers.
% The second-degree polynomial model of the data is given by the equation
% y = -0.2942t^{2}+1.0231t+0.4981.
%
% Evaluate the polynomial at uniformly spaced times, t2. Then, plot the original data and the model on the same plot.

t2 = 0:0.1:2.8;
y2 = polyval(p,t2);
figure
plot(t,y,'o',t2,y2)
title('Plot of Data (Points) and Model (Line)')

%
% Evaluate model at the data time vector

y2 = polyval(p,t);

%
% Calculate the residuals.

res = y - y2;

%
% Plot the residuals.

figure, plot(t,res,'+')
title('Plot of the Residuals')

% Notice that the second-degree fit roughly follows the basic shape of the data, but does not capture the smooth curve on which the data seems to lie. There appears to be a pattern in the residuals, which indicates that a different model might be necessary. A fifth-degree polynomial (shown next) does a better job of following the fluctuations in the data.
%
% Repeat the exercise, this time using a fifth-degree polynomial from polyfit.

p5 = polyfit(t,y,5)

%
% Evaluate the polynomial at t2 and plot the fit on top of the data in a new figure window.

y3 = polyval(p5,t2);   
figure
plot(t,y,'o',t2,y3)
title('Fifth-Degree Polynomial Fit')

% Copyright 2015 The MathWorks, Inc.