% fixedpointfun
function xr = fixedpointfun2(fun,x0)
% Demonstration of Fixed-Point Iteration Method
%
% The input function should be of the form x = g(x)
%      
% Then call fixedpoint to find its roots
% xr = fixedpointfun(@fun,x0)
%
% For Example 4.5 use:
% fixedpointfun2(@(x) cos(x),0.1) 
%
% For Example 4.6 use:
% fixedpointfun2(@(x) sin(5*x)+cos(2*x)+x,-0.9)
%
% For Example 4.7 use:
% fixedpointfun2(@(x) 10./(x.^3 - 1), 2)

close all
clc

pmin = 0; % x limits of the plot. Change for different functions if needed.
pmax = 1;

% First plot g(x) and y=x to see the behaviour
figure
hold on
fplot(@(x) fun(x),[pmin,pmax],'LineWidth',2)
fplot(@(x) x,[pmin,pmax],'LineWidth',2)
fplot(0,[pmin,pmax],'-k')
ylim([0,1]) % y limits of the plot. Change for different functions if needed.
xlabel('x')
ylabel('g(x)')
title('Fixed-Point Iteration Demo')
grid on

% Initialize variables
es = 0.001;
maxit = 100;

% prepare the output header
fprintf('\n  #         xi          er\n');

count = 0;  % iteration counter
er = 1;     % initial error value to enter loop
xi = x0;     % initialize xi and xold
xold = xi;
fxold = fun(xold); % will be used for plotting

fprintf('%3g %10.6g %10.4g\n',count,xi,er);
plot([xold,xold],[xold,fxold],'--k');  % allows us to visualize the approximations

erplot = zeros(1,50);

% main loop
while (abs(er) > es && count<maxit)
    count = count +1;
    xold = xi;  % keep the previous estimate
    fxold = fun(xold); % will be used for plotting
    
    xi = fun(xi);   % calculate the new estimate
    fxi = fun(xi);
    
    plot([xold,xi,xi],[fxold,xi,fxi],'--k');  % allows us to visualize the approximations
       
    er = (xi-xold)/xi;  % relative error
    erplot(count) = er;
   
    fprintf('%3g %10.6g %10.4g\n',count,xi,er);
    % pause  % Wait for key press
end

if count >= maxit
    disp(' ')
    disp(['Failed to converge in ',num2str(maxit),' iterations'])
    disp(' ')
    disp('--------------------------------------------')
    disp(' ')
    xr = NaN;
else
    disp(' ')
    disp(['Root has been found at x = ',num2str(xi)])
    disp(' ')
    disp('--------------------------------------------')
    disp(' ')
    xr = xi;
end

figure
hold on
fplot(0,[0,count],'-k')
plot(erplot(1:count),'LineWidth',2)
title('Relative Error')
xlabel('Iteration Number')
ylabel('Relative Error (er)')
hold off

