%Author: Thomas Lee
function cobweb(x0,tol,a,b,n)
%function cobweb(x0,tol,a,b,n)
%x0=starting iteration value for x
%tol=how small you want the difference to be between adjacent iteration values
%a=lower x bound
%b=upper x bound
%n=number of x values you want to have between a and b
%
% EX:
%
%cobweb(0.01,1e-20,0,1,100)
format compact
fs=25;
lw=2;
xx=linspace(a,b,n);
%cub=inline('(3.*x-x.^3)./2');
%cub=inline('2*x.*(1-x)');
cub=inline('3.3*x.*(1-x)'); % period-2
cub=inline('3.5*x.*(1-x)'); % period-4
cub=inline('3.55*x.*(1-x)'); % period-8
cub=inline('3.565*x.*(1-x)'); % period-16
w=cub(xx);
yy=xx;
figure(1);%clf;
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
xlabel('x_n')
ylabel('x_{n+1}')
plot(xx,w,xx,yy)
plot(xx,xx*0,'k')
plot(xx*0,xx,'k')
i=1;
x(i)=x0;
x(i+1)=cub(x(i));
plot([x(i),x(i)],[0,x(i+1)],'r')
fprintf('x(%d)=%1.20f\n',i,x(i));
while (((abs(x(i+1)-x(i))>tol && abs(x(i+1))<3) || i<5) && min(abs(x(end)-x(1:end-1)))>tol)
i=i+1;
x(i+1)=cub(x(i));
plot([x(i-1),x(i)],[x(i),x(i)],'r')
plot([x(i),x(i)],[x(i),x(i+1)],'r')
fprintf('x(%d)=%1.20f\n',i,x(i));
axis tight
pause
end
%funcvalues=x'
%iter=length(x)