%USPOP2: MATLAB script M-file that uses a 
%central difference derivative approximation
%to approximate parameter values for a logistic
%model to U.S. population growth
%
%Define data
uspop;
%
dydt = (pops(3:end)-pops(1:end-2))/20;
plot(pops(2:end-1),dydt./pops(2:end-1),'o')
title({'Plot of per capita growth vs populations', 'central differences'},...
    'Interpreter','latex','FontSize',16)
xlabel('Populations','Interpreter','latex','FontSize',14)
ylabel('Per capital growth rate','Interpreter','latex','FontSize',14)
pause
p=polyfit(pops(2:end-1),dydt./pops(2:end-1),1);
r=p(2)
K= -r/p(1)
pause
%
%Plot regression line
plot(pops(2:end-1),dydt./pops(2:end-1),'o',pops(2:end-1),p(1)*pops(2:end-1)+p(2))
title({'Plot of per capita growth vs populations',...
    'central differences, with regression line'},...
    'Interpreter','latex','FontSize',16)
xlabel('Populations','Interpreter','latex','FontSize',14)
ylabel('Per capital growth rate','Interpreter','latex','FontSize',14)
pause
%
%Plot ODE solution vs data
y0 = pops(1);
logistic = @(t) y0*K./(y0+(K-y0)*exp(-r*t));
modelpops = logistic(decades);
plot(decades, pops, 'o', decades, modelpops)
title({'Plot of data and model', 'parameters found by central differences'},...
    'Interpreter','latex','FontSize',16)
xlabel('Decades, 1790-2020','Interpreter','latex','FontSize',14)
ylabel('U. S. Populations','Interpreter','latex','FontSize',14)