Search code examples
matlabmethods

Matlab Ridder's Method Code


I need to write a proper implementation of the Ridder's method in Matlab. I must define the function as

function [x sol, f at x sol, N iterations] = Ridders(f, x1, x2, eps f, eps x)

The explanation I was given is:

  1. bracket the roots (x1, x2)

  2. evaluate the midpoint (x1 + x2)/2

  3. find new approximation for the root

    x4 = x3 + sign(f1 - f2) [f3/((f3)^2 - f1f2)^1/2)](x3 - x1)

  4. check if x4 satisfies the convergence condition. if yes, stop. if not...

  5. rebracket the root using x4 and whichever of x1, x2, or x3 is closer to the root

  6. loop back to 1

I have no idea how to implement this in matlab. Help?


Solution

  • In Matlab, you would define your function as:

    function [list of outputs] = myfunc(list of input variables)
    
        %function definition to compute outputs using the input variables.
    

    In your case if you would like x4 (i.e root) to be your output, you would do:

    function root  = riddler(func, x1, x2, xaccuracy, N)
    
    
        xl = x1;
        xh = x2;
        fl=func(x1)
        fh=func(x2)
    
       for i = 1:N
           xm = 0.5*(xl+xh);
           fm = func(xm);
           s = sqrt(fm*fm - fl*fh)
           if s == 0
             return;
           end
           xnew = xm + (xm - xl)*sign(fl - fh)*fm/s %update formula
           .
           .
           . % extra code to check convergence and assign final answer for root 
           . % code to update xl, xh, fl, fh, etc. (i.e rebracket)
           .
    
        end % end for