function cobweb(f,a,b,x0,N)
% Generate a cobweb plot for the orbit x_n+1=f(x_n).
% f - function
% (a,b) - plot interval
% x0 - initial point.
% N - number of iterates
%
% example usage:
%   cobweb(@(x) 2.5*x.*(1-x),0,1,.5,100)
%   cobweb plot for f(x)=2.5x(1-x) on the interval [0,1]
%   starting at 0.5, 100 iterations

% prevent plot from being erased by each graph
hold on;

% generate N linearly spaced values on (a,b)
x=linspace(a,b,50);
plot(x,f(x),'k'); % plot the function in black
plot(x,x,'r'); % plot the straight line in red

% compute iterates and draw cobweb lines
xn=x0; % start at x0
for i=1:N
    disp(xn);  % display xn in the command window
    xnp = f(xn);
    line([xn,xn],[xn,xnp]);    % vertical
    line([xn,xnp],[xnp,xnp]);  % horizontal
    xn = xnp;  % move to next value
end

hold off;
