function spider(f,p0,k)
% SPIDER  Draw "spiderweb" plot of fixed point iteration.
%    spider(f,p0,k)
% where
%    f  = a function f(x) with range in [0,1]
%    p0 = an initial value in [0,1]
%    k  = number of iterations to illustrate
%
% Example I:  stable
%   >> f = @(x) cos(x);
%   >> spider(f,0.5,15)
%
% Example II:  chaotic
%   >> f = @(x) 3.8*x.*(1-x);
%   >> spider(f,0.1,30)
%
% author: Samantha MacNeith; Bueler added a help section

% store iteration
p = p0; 
P = zeros(1,k);
for n = 1:k;
    p = f(p);
    P(n) = p;
end

% plot the fixed point iteration on their unique intervals
%   between the curves y = x and y = f(x)
plot([p0, p0], [0,P(1)], 'm', [p0, P(1)], [P(1),P(1)] , 'g')
hold on
for n= 1:k-1;
   plot([P(n),P(n)], [P(n),P(n+1)], 'm', [P(n), P(n+1)], [P(n+1), P(n+1)], 'g')
   hold on
end

% plot the functions y(x) and f(x)
x = 0:.001:1;
y = @(x) x;
plot (x, y(x), 'b', x, f(x), 'b')
hold off, xlabel x, grid on
axis([0 1 0 1])

