function fitpractice
clear all
dates=1900:10:2000;
time=dates-1900;
pop=[75.995 91.972 105.711 123.203 131.669 150.697 179.323 203.212 226.505 249.633 281.422];
coefs=polyfit(time,pop,1);
ymodel=polyval(coefs,time);
plot(time,pop,'o',time,ymodel)
xlabel('time (years since 1900)')
ylabel('population (millions)')
title('linear fit')
disp('Pop in 2010 predicted from linear fit to be ...')
y2010=polyval(coefs,110)
disp('Press any key to continue')
pause
coefs=polyfit(time,pop,2);
ymodel=polyval(coefs,time);
plot(time,pop,'o',time,ymodel)
xlabel('time (years since 1900)')
ylabel('population (millions)')
title('quadratic fit')
disp('Pop in 2010 predicted from quadratic fit to be ...')
y2010=polyval(coefs,110)
disp('Press any key to continue')
pause
coefs=polyfit(time,pop,3);
ymodel=polyval(coefs,time);
plot(time,pop,'o',time,ymodel)
xlabel('time (years since 1900)')
ylabel('population (millions)')
title('cubic fit')
disp('Pop in 2010 predicted from cubic fit to be ...')
y2010=polyval(coefs,110)
disp('press any key to continue')
pause

dates=1900:10:2000;
time=dates-1900;
pop=[75.995 91.972 105.711 123.203 131.669 150.697 179.323 203.212 226.505 249.633 281.422];
numpts=size(time);
zin(1)=80;
zin(2)=1/30;
zout=fminsearch(@(z) sumoferrspop(z,time,pop), zin);
yplot=curvepop(time,zout);
plot(time,pop,'+',time,yplot)
xlabel('time (years since 1900)')
ylabel('population (millions)')
title('nonlinear fit')
y2010=curvepop(110,zout);
fprintf('nonlinear fit predicts 2010 population of %f \n',y2010)

function f=sumoferrspop(z,time,pop)
f=sum((curvepop(time,z)-pop).^2);

function f=curvepop(x,z)
K=z(1);
alpha=z(2);
f=K*exp(alpha*x); 