Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Bisection method in Matlab

  1. Oct 30, 2012 #1
    Here is the code I have, but I keep getting the error message: Undefined function 'f' for input arguments of type 'double'.

    I don't know what I have that is causing this. Does anybody see what's wrong with my code?

    MaxIt = 1000;
    epsilon = 10^-5;
    c = (b+a)/2;
    NumIt = 0;
    while NumIt< MaxIt && abs(f(c))>epsilon
    if f(a)*f(c) < 0
    b = c;
    a = c;
    NumIt = NumIt + 1;
    c = (b+a)/2;
    function y = f(x)
    y = exp(x)-2^-x+2*cos(x)-6;
    Undefined function 'f' for input arguments of type 'double'.
  2. jcsd
  3. Oct 30, 2012 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    As written, you would need to store your function f(x) in a separate Matlab file named f.m. You can't have local functions in a Matlab script file. You can have local functions in a Matlab function file, so one way to avoid having a separate file for that tiny function is to turn your script into a Matlab function.

    This is such a short and simple function that may not even want to do that. Another option is to use an anonymous function instead. Define f(x) via f = @(x) exp(x)-2^-x+2*cos(x)-6; You'll need to put this near the top of your script rather than at the bottom.
  4. Oct 30, 2012 #3
    Okay, that worked great! Thank you.

    Last question, just because I have a hard time in Matlab.
    When I'm looking at the solution, do I want to display c or f(c) to get the root? It would be c, correct?
  5. Oct 30, 2012 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    c, of course. f(c) will be close to zero -- in this case. Try this, however:
    • Change MaxIt to 1024 or so (adjust downward if you get divide by zero).
    • Change the initial value of a from +1 to -1.
    • Change your function to f = @(x) 1/x;
    It's worthwhile to print either f(c) or NumIt (or both) to see if the algorithm truly did converge on a zero.
    Last edited: Oct 30, 2012
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Similar Threads for Bisection method Matlab Date
Mathematica Solve Perturbation problem with mathematica Dec 7, 2017
MATLAB "Linear Model" of a Pendulum via Euler's Method Nov 16, 2016
Comparing direct and iterative solution of linear equations Nov 8, 2016
MATLAB Bisection method and numerical integration Apr 14, 2016