"Unrecognized function or variable" error when using fminbnd on an anonymous function

Any time I call an anonymous function in fminbnd, an error is returned, particularly with this code:
f=@(x) x^3;
g=@(x) 4*cos(x);
h=@(x) 6*exp(g(f(x)));
fminbnd(@h, -10, 10)
The error is:
Unrecognized function or variable 'h'.
Error in fminbnd (line 233)
x= xf; fx = funfcn(x,varargin{:});
Error in Homework8 (line 25)
fminbnd(@h, -10, 10)
If I copy the code and paste it into its own function file and then try to use fminbnd, it works as intended.

回答 (2 件)

Here, h is already defined as a function handle, so the '@' is not necessary, and is in fact causing the error.
Try this.
f=@(x) x^3;
g=@(x) 4*cos(x);
h=@(x) 6*exp(g(f(x)));
fminbnd(h, -10, 10)
ans = -7.2440
h is already a function handle, there's no need to try to make it one again.
f1 = @sin; % Regular function handle
f2 = @(x) x.^2; % Anonymous function (also a function handle)
h = @(x) f1(x)+f2(x); % Another function handle
fminsearch(h, pi/2)
ans = -0.4501

2 件のコメント

REMYA R suresh
REMYA R suresh 2022 年 4 月 8 日
Error in cuu (line 24)
fx=fns(nest);
how to rectify this error ?
Torsten
Torsten 2022 年 4 月 8 日
Difficult to say without your code.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

製品

リリース

R2020b

質問済み:

2021 年 3 月 19 日

コメント済み:

2022 年 4 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by