Finding the minimum of a function

My function is supposed to return the minimum y-value, fmin, of the function described in the input function handle, funhan, in the interval, [x1, x2]. What am I doing wrong?
function fmin = findMin(funhan, x1, x2)
[~, fmin] = fmindbnd(@funhan(x),x1,x2);
and I already wrote the pre-exisiting function square_plus_one (which will be called in the test case)
function y = square_plus_one(x)
y= x.^2 + 1
These are what the Test Cases are supposed to run--but i can't run the test cases without an error
>> fh = @square_plus_one;
>> low = 3; hi = 5;
>> findMin(fh,low,hi)
ans = 10.0003
>> fh = @cos;
>> low = 3; hi = 4;
>> findMin(fh,low,hi)
ans = -1.0000

댓글 수: 2

Star Strider
Star Strider 2012년 10월 14일
I don't see any errors. What were you expecting?
Walter Roberson
Walter Roberson 2012년 10월 14일
The minimum of x^2+1 over 3 to 5 would be 10 not 10.0003

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2012년 10월 14일

0 개 추천

Just pass funhan to fminbnd() instead of passing @funhan(x)
Alternately pass @(x) funhan(x)

댓글 수: 6

Ping
Ping 2012년 10월 14일
walter: when i change my code to
[~, fmin] = @(x) (funhan(x),x1,x2);
I get the error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
and when i change it to
[~, fmin] = @(x) (fminbnd(),x1,x2);
i get the same error! i don't understand the error because all my parenthesis and brackets are in place!
[~, fmin] = fmindbnd(funhan,x1,x2);
or
[~, fmin] = fmindbnd(@(x) funhan(x),x1,x2);
Ping
Ping 2012년 10월 15일
for the 1st one i get the error: Undefined function 'fmindbnd' for input arguments of type 'function_handle'.
for the 2nd one I get the error: Undefined function 'fmindbnd' for input arguments of type 'function_handle'.
Which MATLAB version are you using? fminbnd is part of basic MATLAB now. What does
which -all fminbnd
show ?
Ping
Ping 2012년 10월 15일
/Applications/MATLAB_R2012a_Student.app/toolbox/matlab/optimfun/fminbnd.m EDU>>
Walter Roberson
Walter Roberson 2012년 10월 15일
fmindbnd() is the same place it was for your original question where you used that function ;-)
Possibly you had a typo in your question and meant to type fminbnd at that point, and that fminbnd is what you want to use here.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Strategy & Logic에 대해 자세히 알아보기

태그

질문:

2012년 10월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by