% This MATLAB code implements the Secant method to solve for roots of the
% input equation myfun with derivative myfunprime.
% Call as newton(initapprox1,initapprox2,'myfun',tol)
function[x]=secant(x_1,x_2,myfun,tol)
% Set up iteration control
maxiter=10000; i = 1;
% Set up initial approx
nextadjust=feval(myfun,x_1)*(x_1-x_2)/(feval(myfun,x_1)-feval(myfun,x_2));
x=x_1-nextadjust;
abs(feval(myfun,x))
while abs(feval(myfun,x))>=tol && i<=maxiter;
    x_2=x_1;
    x_1=x;
    % Implement the Secant formula to update the approximation
    x=x-nextadjust;
    % Update iteration count
    i=i+1;
    % Print a message if maximum iteraton is reached:
    if i==maxiter;
        fprintf('Max number of %d iterations reached; root may not\n',maxiter);
        fprintf('have been found to within tolerance\n');
    end;
    nextadjust=feval(myfun,x_1)*(x_1-x_2)/(feval(myfun,x_1)-feval(myfun,x_2));
end;
fprintf('%d iterations\n',i);