What is wrong with my bisection method code?
显示 更早的评论
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!
采纳的回答
更多回答(1 个)
John BG
2018-2-23
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 个评论
John D'Errico
2018-2-24
Except that the homework problem was probably to write a bisection FUNCTION, not a script that does bisection.
Jan
2018-2-24
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
2018-2-24
nothing more nothing else than a syntax correction, that is all that was needed.
类别
在 帮助中心 和 File Exchange 中查找有关 Desktop 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!