0001 function [ x,k ] = secant_method( f,a,b,tol,max )
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013 if a>=b;
0014 error('specifed interval invalid');
0015 elseif tol<=0;
0016 error('tol must be positive');
0017 elseif max<=0;
0018 error('max must be positive');
0019 elseif isa(f,'function_handle');
0020
0021 elseif isa(f,'double');
0022 [n,m]=size(f);
0023 if n~=1 && m~=1;
0024 error(['Input must be a function handle or vector holding ',...
0025 'polynomial coefficients']);
0026 else
0027 v=poly2sym(f);
0028
0029 f=matlabFunction(v);
0030
0031 end
0032 else
0033 error(['input must be a function handle or vector holding ',...
0034 'polynomial coefficients']);
0035 end
0036
0037
0038 fa=feval(f,a);
0039 fb=feval(f,b);
0040 k=0;
0041
0042 if fa==0;
0043 x=a; return;
0044 elseif fb==0;
0045 x=b; return;
0046 end
0047 fc=fb;
0048
0049 while abs(fc)>tol && k<=max;
0050
0051 denom=fb-fa;
0052 if abs(denom)<1e-12;
0053 disp(['denominator gets very close to zero, possible'...
0054 'loss of significance'])
0055 end
0056
0057 c=b-fb*((b-a)/(denom));
0058
0059 fc=feval(f,c);
0060 a=b;
0061 b=c;
0062 fa=fb;
0063 fb=fc;
0064
0065 k=k+1;
0066 end
0067
0068 x=c;
0069
0070 if k==max+1;
0071 disp('maximum number of iterations reached');
0072 end
0073
0074 end