Trying to do bisection, new to MATLAB

1 view (last 30 days)
James Cortez
James Cortez on 5 Oct 2018
Edited: James Cortez on 6 Oct 2018
My code is:
function f = bisection2(g,a,b)
g= @x 3*x - e^x
while 1
p =(a+b)/2;
if p-a< 10^-5, break;end
if g(a)*g(p)>0
a = p;
else
b = p;
end
end %while 1
I have tried defining g in a separate .m file, but I keep getting an error in that line. 3x-e^x is the function I am trying to apply bisection to. I am using R2018b.

Answers (1)

ANKUR KUMAR
ANKUR KUMAR on 5 Oct 2018
As your equation negative value at both ends. So bisection can not be possible for your equation. I am giving this example by taking different function.
g= @(x) 2*x + sin(x)
bisection(g,-5,10)
function p = bisection(f,a,b)
f(a)
f(b)
if f(a)*f(b)>0
disp('The function has positive value at the end points of interval.');
disp('The root can''t be found using bisection method, use some other method.');
else
p = (a + b)/2;
err = abs(f(p));
while err > 1e-7
if f(a)*f(p)<0
b = p;
else
a = p;
end
p = (a + b)/2;
err = abs(f(p));
end
end
end
References:
  1 Comment
James Cortez
James Cortez on 6 Oct 2018
Edited: James Cortez on 6 Oct 2018
Figured out what I was doing wrong. I was trying to initiate g inside a .m file instead of putting
"g= @(x) 3*x - exp(x)" into the command window. Hopefully this will help someone else that is just starting out.

Sign in to comment.

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!