%------cobweb plot of the iteration x(n+1)=f(x(n))--------% 

function cobweplot
 
clear; 

%------compute the trajectory-----------------%
	
	x0=1.1        % initial condition 
	N=100;           % number of iterations
	x(1) = x0;      % set the initial condition 
    xmin = -4; % set the minimum value of x
    xmax = 4; % set the maximum value of x
	for time =1:N
		x(time + 1) =  f(x(time)); 
    end
    
%------cobweb plot-------------%    
    subplot(1,2,1);
    
    hold off; 
	t = xmin :0.01: xmax;
	plot(t,f(t)); hold on;  
    % axis([0 1 0 1]);
	%set(gca,'XTick',(0:0.1:1),'YTick',(0:0.1:1))
	grid off;
	fplot('1*y',[xmin xmax],'r');


%-------cobweb plot----------------------------% 
	line([x(1) x(1)],[0 x(2)],'Color','g') 
	plot(x(1), x(1),'ko');
	for time=1:N-1
		line([x(time) x(time+1)],[x(time+1) x(time+1)],'Color','g')  
		line([x(time+1) x(time+1)],[x(time+1) x(time+2)],'Color','g')
		plot(x(time+1), x(time+1),'ko');
	end
	line([x(N) x(N+1)],[x(N+1) x(N+1)],'Color','g')
 
%-------captions--------------------------------% 

	captions=text(0.1,0.82,['\lambda =',num2str(lambda)]); 
	set(captions,'FontSize',12);
    xlabel('x');
    ylabel('x');
    title('cobweb plot');
   
%--------drow the trajectory: n versus x(n)------------------------% 

    subplot(1,2,2);
    %axis([0 1 0 1]);
    t = 1:1:N;
    y = x(t); 
    plot(t,y,'r+');
    xlabel('time');
    ylabel('x');
    title('trajectory');
    
    
%-----------define the function f(x)----------%

function funzione = f(x)
lambda = 0.99; % parameter lambda
funzione = x.^2-2; %----- logistic
end

end

 
