function y = fixpoint(fname, s, n, tol, xexact, range)
% FIXPOINT - Visualize fixed point iteration
% usage: fixpoint(fname, s, n, tol, xexact, range)')
%
% s      : iteration start point
% fname  : function handle
% n      : maximum number of iterations
% tol    : max change of x value to allow abort
% xexact : exact fix point (for error plot)
% range  : plot range (e.g. [0 1]): OPTIONAL
%
% if range is omitted, the default range is the full iteration range.

% Author : B. Wohlmuth, A. Klimke 
% Date   : Mai 2002
% Version: 1.0
	
% Check number of arguments.
if (nargin ~= 5 & nargin ~=6 & nargin)
  error('For usage please type "help fixpoint"');
end

% Retrieve function variable names
variables = symvar(fname);

% Initialize
dx = 1;
tol = min(tol, 1);
count = 1;
y(count) = s;

% Perform fix point iteration
while (count < n & dx >= tol)
	y(count+1) = feval(fname, y(count)); 
	dx = abs(y(count+1) - y(count));
  count = count + 1;
end

% Generate result string
result = sprintf(['  Approx. for n=' num2str(count) ': ' ...
					variables{1} '=' num2str(y(end)) ]);

% Draw first figure: The error plot
clf;
subplot(2,1,2);

% draw absolute error
semilogy(abs(y-xexact), 'bd-','LineWidth', 2);

% Format graph
set(gca, 'FontSize',10);
xlabel('number of iterations','FontSize', 10);
ylabel('absolute error','FontSize', 10);

XText = min(get(gca,'XLim'));
YText = min(get(gca,'YLim'));
h = text(XText, YText, sprintf(result));
set(h, 'FontSize',10);
set(h, 'VerticalAlignment', 'bottom');
grid;

% Draw second figure: Iteration plot
subplot(2,1,1);

% Create default range if range information was omitted
if (nargin==5) 
	range = [min([xexact y]), max([xexact y])]
end

x = linspace(min(range),max(range),100);

hold on;

% Draw horizontal & vertical lines
for k = 1:length(y)-1
plot(y(k:k+1), feval(fname, [y(k) y(k)]),'g','LineWidth', 1);
plot([y(k+1) y(k+1)], feval(fname, y(k:k+1)),'g','LineWidth', 1);
end

% Draw bisection of angle
plot([min(x) max(x)],[min(x) max(x)], 'LineWidth', 2);
% Draw function
plot(x,feval(fname,x),'r','LineWidth', 2)

% Plot iteration values
plot(y,feval(fname,y),'kx', 'LineWidth', 2)

% Format graph
set(gca, 'FontSize',10);
XText = min(get(gca,'XLim'));
YText = max(get(gca,'YLim'));
h = text(XText, YText, result);
set(h, 'FontSize',10);
set(h, 'VerticalAlignment', 'top');
set(h, 'HorizontalAlignment', 'left');
title(['Fixpoint Iteration for f(' variables{1} ')=' ...
			 char(fname) '   Starting value: ' variables{1} ...
			 '='  num2str(s)],'FontSize', 10);

xlabel(variables{1},'FontSize', 12);
ylabel(['f(' variables{1} ')'],'FontSize', 10);
grid;