%USPOP3: MATLAB script M-file that uses MATLAB's built-in
%least squares regression function lsqcurvefit to find 
%least squares values for r, K, and y0, for a logistic
%fit of U.S. population data
%
%define data
uspop;
%Define logistic solution
y = @(p,t) p(2)*p(3)./(p(3)+(p(2)-p(3))*exp(-p(1)*t));
%Initial estimate of parameters
%Forward differences
%p0 = [.0314 335.3112 pops(1)];
%Central differences
p0=[.0277 362.3526 pops(1)];
[p ssr]=lsqcurvefit(y,p0,decades,pops)
N=length(decades); m = length(p);
q = N-m;
sd=sqrt(ssr/q)
%Adjusted coefficient of determination: keep in mind that 
%it's not entirely clear what this means for nonlinear regression.
popsbar = mean(pops);
T = norm(pops-popsbar)^2;
Rsq = 1-ssr/T
Rsqa = 1-(1-Rsq)*(length(decades)-1)/q
pause
%
%Plot model along with data
modelpops = y(p,decades);
plot(decades,pops,'o',decades,modelpops)
title({'Plot of data and model', 'parameters found by nonlinear regression'},...
    'Interpreter','latex','FontSize',16)
xlabel('Decades, 1790-2020','Interpreter','latex','FontSize',14)
ylabel('U. S. Populations','Interpreter','latex','FontSize',14)
%Prediction for 2020
disp(['The prediction for 2030 is ' num2str(y(p,240)) ' +/- ' num2str(sd)])