What is wrong with my bisection method code?
Show older comments
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!
Accepted Answer
More Answers (1)
John BG
on 23 Feb 2018
Hi Microwave97
Now your code doesn't show syntax errors:
f=@(x) exp(2*x) - 3*x -4 % use your support function instead
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)*f(r) <= 0)
b = r ;
else
a = r;
end
end
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance for time and attention
John BG
3 Comments
John D'Errico
on 24 Feb 2018
Except that the homework problem was probably to write a bisection FUNCTION, not a script that does bisection.
Jan
on 24 Feb 2018
To be exact, he question was:
Can someone help me find what's wrong with my MatLab code for
the bisection method?
"Undefined function or variable 'a'.
What does this mean?
Converting the function to a script and using an anonymous function instead of a function does not concern these questions. Posting a version without syntax errors is not useful, because the code is still not a valid bisection method due to the missing application of tol.
John BG
on 24 Feb 2018
nothing more nothing else than a syntax correction, that is all that was needed.
Categories
Find more on Desktop in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!