Finding a root of f(x) = cos(x):
eps_step = 1e-5;
eps_abs = 1e-5;
N = 100;
xp = 1.0;
xc = 1.1;
for i=1:N
xn = (xc*cos(xp) - xp*cos(xc))/(cos(xp) - cos(xc));
if abs( xc - xn ) < eps_step && abs( cos( xn ) ) < eps_abs
break;
elseif i == N
error( 'the secant method did not converge' );
end
xp = xc;
xc = xn;
end
xn
Of course, you can always cheat and use the built-in functions:
for i=1:N
px = polyfit( [xp, xc], cos([xp, xc]), 1 );
xn = roots( px ); % there can only be one...
...
end
Copyright ©2005 by Douglas Wilhelm Harder. All rights reserved.


