%% Programmatic Fitting
%% Load Sample Data
% Load sample census data from census.mat, which contains U.S. population data from the years 1790 to 1990.

load census

% This adds the following two variables to the MATLAB workspace.
% cdate is a column vector containing the years 1790 to 1990 in increments of 10.
% pop is a column vector with the U.S. population numbers corresponding to each year in cdate.
%
% Plot the data.

plot(cdate,pop,'ro')
title('U.S. Population from 1790 to 1990')

% The plot shows a strong pattern, which indicates a high correlation between the variables.
%
%% Calculate Correlation Coefficients
% Calculate the correlation-coefficient matrix.

corrcoef(cdate,pop)

% The diagonal matrix elements represent the perfect correlation of each variable with itself and are equal to 1. The off-diagonal elements are very close to 1, indicating that there is a strong statistical correlation between the variables cdate and pop.
%
%% Fit a Polynomial to the Data
% Calculate fit parameters.

[p,ErrorEst] = polyfit(cdate,pop,2);

%
% Evaluate the fit.

pop_fit = polyval(p,cdate,ErrorEst);

%
% Plot the data and the fit.

plot(cdate,pop_fit,'-',cdate,pop,'+');
title('U.S. Population from 1790 to 1990')
legend('Polynomial Model','Data','Location','NorthWest');
xlabel('Census Year');
ylabel('Population (millions)');

% The plot shows that the quadratic-polynomial fit provides a good approximation to the data.
%
% Calculate the residuals for this fit.

res = pop - pop_fit;
figure, plot(cdate,res,'+')
title('Residuals for the Quadratic Polynomial Model')

% Notice that the plot of the residuals exhibits a pattern, which indicates that a second-degree polynomial might not be appropriate for modeling this data.
%
%% Plot and Calculate Confidence Bounds
% Evaluate the fit and the prediction error estimate (delta).

[pop_fit,delta] = polyval(p,cdate,ErrorEst);

%
% Plot the data, the fit, and the confidence bounds.

plot(cdate,pop,'+',...
     cdate,pop_fit,'g-',...
     cdate,pop_fit+2*delta,'r:',...
     cdate,pop_fit-2*delta,'r:'); 
xlabel('Census Year');
ylabel('Population (millions)');
title('Quadratic Polynomial Fit with Confidence Bounds')
grid on

% Copyright 2015 The MathWorks, Inc.