How can I get my bisection method function to work?

3 views (last 30 days)
I'm trying to write a bisection method algorithm to evaluate the minimum of a one variable function. I keep getting this error when i enter the command 'Fmin=bisection(4,6,10.^-3,F)':
"Undefined function 'bisection' for input arguments of type 'function_handle'. "
Can someone please help me figure out what I'm doing wrong?
My code is:
if true
% code
end
function Fmin = bisection(a,b,e,F)
%BISECTION METHOD Input endpoints of starting and function to optimise over %four intervals and Fmin will output as local minimum.
xa=a;xb=b;xm=(a+b)./2;
while abs(xb-xa)>e
F=feval(F,x);
Fa=F(xa),Fb=F(xb),Fm=F(xm);
xl=(xa+xm)./2,xr=(xm+xb)./2;
Fl=F(xl),Fr=F(xr);
y=[Fa,Fb,Fm,Fl,Fr];
Fmin=min(y);
if Fmin==Fa,
xb=xm,xm=xl,Fb=Fm,Fm=Fl;
elseif Fmin==Fl,
xb=xm,xm=xl,Fb=Fm,Fm=Fl;
elseif Fmin==Fb,
xa=xm,xm=xr,Fa=Fm,Fm=Fr;
elseif Fmin==Fr,
xa=xm,xm=xr,Fa=Fm,Fm=Fr;
elseif Fmin==Fm,
xa=xl,xb=xr,Fa=Fl,Fb=Fr;
end
end
fprintf(Fmin)
end
I'm using this for function F:
if true
% code
end
function F=f(x)
F=((x-1).^2).*((x-3).^2).*((x-5).^2)-5.*x;
end

Accepted Answer

the cyclist
the cyclist on 8 Feb 2013
I think you may have multiple problems with this code, but let's start at the beginning. Is your function saved in an M-file named bisection.m, in a directory in your path? What do you get if you type
>> which bisection
at the command line?
  3 Comments
the cyclist
the cyclist on 8 Feb 2013
If I understand your code correctly, you don't need that line that is giving you the error. Comment it out. The function F that you pass in will just operate directly on its arguments (like F(xa)).
I am calling bisection like this:
>> Fmin=bisection(4,6,10.^-3,@F)
Next, I get an error from your fprintf command. You could use
fprintf('%6.4f',Fmin)
or just use
disp(Fmin)

Sign in to comment.

More Answers (0)

Categories

Find more on Language Fundamentals 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!