function [root,ea,iter]=secantmethod(func,xr,xo,es,maxit,varargin) % Secant method that uses numerical derivative to find the solution % % input: % func = name of function % xr = initial guess % xo = the second x value from which to calculate the numerical derivative % es = desired relative error (default = 0.0001%) % maxit = maximum allowable iterations (default = 50) % p1,p2,... = additional parameters used by function % output: % root = real root % ea = approximate relative error (%) % iter = number of iterations if nargin<3,error('at least 3 input arguments required'),end if nargin<4|isempty(es),es=0.0001;end if nargin<5|isempty(maxit),maxit=50;end iter = 0; % Define x step size between your two points xstep = xr-xo; while (1) xrold = xr; %xr = xr - func(xr)/dfunc(xr); Newton Raphson method xr = xr - func(xr)*(xo-xr)/(func(xo)-func(xr)); iter = iter + 1; if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end if ea <= es | iter >= maxit, break, end % Define new second x value for slope xo = xr-xstep; end root = xr; end