function [x,fail] = cobweb(g,x,eps,N,xmin,xmax,ymin,ymax) % % On entry : % g function defining the x = g(x); % x start point for the fixed-point iteration; % eps accuracy requirement: stops when two consecutive % approximations in the sequence are % N maximal number of allowed iterations; % xmin minimal value for x to view the graph; % xmax maximal value for x to view the graph; % ymin minimal value for g(x) to view the graph; % ymax maximal value for g(x) to view the graph. % % On return : % x last approximation in the sequence; % fail 0 means success, 1 means failure. % % Example : % >> cobweb('myfun',0.3,1.0e-6,10,0.1,10,0,10) % fprintf('illustration of fixed-point iteration...\n'); xr = xmin:0.1:xmax; % sample range to plot yr = feval(g,xr); % evaluate at the samples figure; % new figure window axis([xmin xmax ymin ymax]); % adjust the scale hold on; % overlay plot plot(xr,yr); % plot the function y = g(x) plot(xr,xr); % plot the diagonal y = x for i = 1:N % perform N iterations y = feval(g,x); % y = g(x) plot([x x],[x y],'g--'); % vertical line plot([x y],[y y],'r--'); % horizontal line fprintf(' x = %e, y = %e, |x-y| = %e\n', x, y, abs(x-y)); if (abs(x-y) < eps) fprintf('succeeded after %d steps\n', i); x = y; fail = 0; return; % terminate with success end; x = y; end; fail = 1; % terminate with failure