1

Hello we have to implement the bisection method to find a root of a function in the interval [a,b]. The algorithm should return 1.the root "c" 2. the function value "yc" 3. number of iterations "itcount".

Here is what I have till now:

   function [ r, c, yc, itcount] = bisection( f, a, b, N, eps )
% Check that that neither end-point is a root
% and if f(a) and f(b) have the same sign, throw an exception.

if ( f(a) == 0 )
r = a;
return;
elseif ( f(b) == 0 )
r = b;
return;
elseif ( f(a) * f(b) > 0 )
    error( 'f(a) and f(b) do not have opposite signs' );
end

% We will iterate N times and if a root was not
% found after N iterations, an exception will be thrown.

for k = 1:N
    % Find the mid-point
    c = (a + b)/2;
    yc = feval(f,c);
    itcount = abs(b-a)/2;
    % Check if we found a root or whether or not
    % we should continue with:
    %          [a, c] if f(a) and f(c) have opposite signs, or
    %          [c, b] if f(c) and f(b) have opposite signs.

    if ( f(c) == 0 )
        r = c;
        return;
    elseif ( f(c)*f(a) < 0 )
        b = c;
    else
        a = c;
    end

    % If |b - a| < eps_step, check whether or not
    %       |f(a)| < |f(b)| and |f(a)| < eps_abs and return 'a', or
    %       |f(b)| < eps_abs and return 'b'.

    if ( b - a < eps )
        if ( abs( f(a) ) < abs( f(b) ) && abs( f(a) ) < eps )
            r = a;
            return;
        elseif ( abs( f(b) ) < eps )
            r = b;
            return;
        end
    end
 end

 error( 'the method did not converge' );
end

I have already created a .m file for the function I want to find the root of. And the algorithm works but it only returns the root but not the function value and the number of iterations. What am I doing wrong?

WaitForIt
  • 131
  • 1
  • 10

1 Answers1

0

Your algorithm seems correct. You should get the output as a vector.

[r, c, yc, itcount] = bisection(@f,.......) 

calling like this will only get you the first element

an = bisection(@f,.......)

see this thread-> MATLAB - multiple return values from a function?

Community
  • 1
  • 1
Kzhunter
  • 597
  • 1
  • 6
  • 19