% Script to work with U.S. National Debt statistics
clear all
load debtstats

% Reexpress year data, make it 0 to 13.
ryear = (yr - 1952) / 4;

% Generate exponential fit
xfun = inline('b(1).*exp(b(2).*x)','b','x');
[bx,rx] = nlinfit(ryear,debt,xfun,[debt(1) .2]);
yxfit = feval(xfun,bx,ryear);
plot(yr,debt,'*',yr,yxfit,'r-')

% Generate logistic fit
figure
lfun = inline('b(1)./(1 + exp((b(2).*x) + b(3)))','b','x');
[bl,rl] = nlinfit(ryear,debt,lfun,[1e4 -1 6]);
ylfit = feval(lfun,bl,ryear);
plot(yr,debt,'^',yr,ylfit,'k-')

% Logistic fit seems off; try logistic fit with added constant
figure
lcfun = inline('b(1)./(1 + exp((b(2).*x) + b(3))) + b(4)','b','x');
[bcl,rcl] = nlinfit(ryear,debt,lcfun,[1e4 -1 6 250]);
ylcfit = feval(lcfun,bcl,ryear);
plot(yr,debt,'v',yr,ylcfit,'m-')

% Use fits to predict debt in 2010.  Reexpress first.

predyr = 2010;
rpred = (predyr - 1952) / 4;

pxfit = feval(xfun,bx,rpred)
plfit = feval(lfun,bl,rpred)
plcfit = feval(lcfun,bcl,rpred)