How can I get my bisection method function to work?

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

 Akzeptierte Antwort

the cyclist
the cyclist am 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 Kommentare

When I first typed that command: 'bisection' could not be found.
I found where it was in the directory and added the folder to the path so when I entered it again I now get: C:\Users\Lulu\Documents\MATLAB\Numerical Optimisation\bisection.m
Running the code I still have an error but it is now:
Undefined function or variable 'x'.
Error in bisection (line 7)
F=feval(F,x);
Thanks for helping!
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)
Lulu
Lulu am 8 Feb. 2013
Thank you, that has fixed it!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Entering Commands finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by