function [root, fx, ea] = FPI(func,xo,error,maxit) % Coded by Nigel F. Reuel on 10.6.2016 % This code uses the fixed point iteration method to attempt solution for a % root. The function must be supplied such that it is of the h(x) form: % h(x) = f(x) + x <-- Add x to the original function f(x) % So that the search finds the intersection of g(x) = x and h(x) ... this is the root % % Note: as the textbook discusses, this diverges IF |h'(x)| > 1 % if nargin<2,error('at least 2 input arguments required'),end if nargin<3||isempty(error), error=0.0001;end if nargin<4||isempty(maxit), maxit=50;end iter = 0; xr = xo; ea = 100; ea_vec = ea; while (1) xrold = xr; xr = func(xr); % Defines next point here iter = iter + 1; if xr ~= 0,ea = abs((xr - xrold)/xr) * 100;end % Track the error for each step ea_vec = [ea_vec ea]; if ea <= error || iter >= maxit,break,end end root = xr; fx = func(xr)-xr; % Plot the error trend to show if the solution converged iter_vec = 1:length(ea_vec); plot(iter_vec-1,ea_vec,'o'); title('Error Trend') xlabel('Iterations') ylabel('Error (%)') end