function cobweb_plot ( f, x0, n, a, b, filename )

%*****************************************************************************80
%
%% cobweb_plot() makes a cobweb plot of a function iteration.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    27 February 2020
%
%  Author:
%
%    Original Python version by John D Cook.
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    John D Cook,
%    Cobweb plots,
%    https://www.johndcook.com/blog/2020/01/19/cobweb-plots/
%    Posted 19 January 2020.
%
%  Input:
%
%    function handle f:
%
%    real x0: the starting point for the iteration.
%
%    integer n: the number of iterations.
%
%    real a, b: the interval.
%
%    string filename: the name of a file in which to save a copy of the plot.
%
  if ( nargin < 1 )
    f = @cos;
  end

  if ( nargin < 2 )
    x0 = 0.5;
  end
  y0 = f ( x0 );

  if ( nargin < 3 )
    n = 20;
  end

  if ( nargin < 4 )
    a = 0.0;
  end

  if ( nargin < 5 )
    b = a + 1.0;
  end

  if ( nargin < 6 )
    filename = 'cobweb_plot.png';
  end

  t = linspace ( a, b, n );

  figure ( );
  clf ( );
  hold ( 'on' );
%
%  Plot the function.
%
  plot ( t, f ( t ), 'k', 'linewidth', 2 );
%
%  Plot the dotted line y = x.
%
  plot ( t, t, 'k:', 'linewidth', 2 );
  grid ( 'on' );
%   
%  Plot the iterates.
%
  x = x0;
  y = y0;
  for i = 1 : n
    fy = f ( y );
    plot ( [x, y], [y,  y], 'b', 'linewidth', 2 );
    plot ( [y, y], [y, fy], 'b', 'linewidth', 2 );
    x = y;
    y = fy;
  end
%
%  Plot the first and last points.
%
  plot ( x0, y0, 'g.', 'markersize', 20 );
  plot ( x, y, 'r.', 'markersize', 20 );

  hold ( 'off' );
%
%  Give x and y axis the same scale.
%
  axis ( 'equal' );
%
%  Save a copy of the figure.
%
  print ( '-dpng', filename );
  fprintf ( '  Graphics saved as "%s"\n', filename )

  return
end

