MATLAB: What is wrong with the bisection method code

variable

Can someone help me find what's wrong with my MatLab code for the bisection method?
This is my code in MatLab:
function [z] = bisect1(a,b,fopg1,tol)
a = 0;
b = 2;
tol = 1e-8;
if (f(a)*f(b) > 0)
error ('invalid choice of interval')
end
r=0;
n=0;
while ((b-a)/2 > 0)
n = n + 1;
r = (a+b)/2;
if (f(r) == 0)
break;
elseif (f(a)*f9=(r) < 0)
b = r ;
else
a = r;
end
end
fopg1 is te function defined in another tab, where
y = exp(2x) – 3x -4
If I run the programme, it displays:
"Undefined function or variable 'a'.
What does this mean?
Thanks!

Best Answer

You don't show us how you are calling this function, so it is hard to advise you what to correct for that.
For the code itself, some comments:
This line gives fopg1 as an input, but your code uses f:
function [z] = bisect1(a,b,fopg1,tol)
So maybe change this line to:
function [z] = bisect1(a,b,f,tol)
I assume the following line is a typo:
elseif (f(a)*f9=(r) < 0)
and should be this instead:
elseif (f(a)*f(r) < 0)
Your function returns a z value but you never set z in your code. Maybe you meant to use r as the return value? E.g.,
function [r] = bisect1(a,b,f,tol)
Finally, you never make use of the tol input. You should have some type of check to see when you meet the tolerance and then exit the function. This will avoid unnecessary calculations and also avoid a potential infinite loop. E.g., if you were to use your code to try to find the value of pi by looking for the root of sin(x) near 3, your current code would end up in an infinite loop. That's because sin(pi) will not be exactly 0 (because of floating point effects), and the (a+b)/2 calculation will eventually degrade and return just a again and you will end up repeating that last iteration over and over again, never quitting and never meeting your current exit criteria. In addition to a tol check, maybe check to see if n gets too large and exit on that condition as well (maybe with an error).