%USPOP3A: MATLAB script M-file that uses MATLAB's built-in
%function fminsearch to 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));
%Define the error
E = @(p) norm(pops-y(p,decades))^2;
%Initial estimate of parameters
%Forward differences
%p0 = [.0314 335.3112 pops(1)];
%Central differences
p0=[.0277 362.3526 pops(1)];
[p ssr]=fminsearch(E,p0)
N=length(decades); m = length(p);
q = N-m;
sd=sqrt(ssr/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)
pause
%Prediction for 2030
disp(['The prediction for 2030 is ' num2str(y(p,240)) ' +/- ' num2str(sd)])