problem of function handles, thx

for instance,
parms=ones(2,1);
myfunc = @(parms) X.*parms(1)+Y.*parms(1);
I can directly indicate 'myfunc' in 'fmincon'. [parms,favl]=fmincon(myfunc,parms,....);
However, if I want to separately write 'myfunc' in a function script and then quote it. [parms,favl]=fmincon(myfunc,parms,....); the 'fmincon' will report 'Not enough input in myfunc'.
X and Y are variables stored in workspace, they are not unknown parameters, only parms(1) and parms(2) required estimation.
anyone can tell me how to solve this problem? many thanks!

 採用された回答

Sean de Wolski
Sean de Wolski 2015 年 1 月 14 日
編集済み: Sean de Wolski 2015 年 1 月 14 日

0 投票

You need an @ before myfunc, otherwise it tries to evaluate it:
@myfunc % reference to function myfunc; do not evaluate
myfunc % when myfunc is its own file tries to run it
myfunc % when myfunc is a function handle (variable), then myfunc is already a reference to whatever

4 件のコメント

Zhixiao
Zhixiao 2015 年 1 月 14 日
編集済み: Zhixiao 2015 年 1 月 14 日
sorry=.= I still do not understand about it, could you please give me some examples? I have read the examples provided by the official website, but I just still do not understand about it... many thanks
Sean de Wolski
Sean de Wolski 2015 年 1 月 14 日
When you say
myfunc = @(x)x^2
myfunc is now a reference to the function x^2.
if you have a file myfunc2:
function y = myfunc2(x)
y = x^2
And say
myfunc2
It is going to try and call myfunc2. Myfunc2 won't run because it needs x, the error you're getting for not enough inputs.
Since you want to create a reference to myfunc2, you say
myfunc2ref = @myfunc2
Now myfunc2ref is a reference just like myfunc above. You can pass this directly into fminunc.
Zhixiao
Zhixiao 2015 年 1 月 15 日
How can I call function y =myfunc2(x) in fmincon? e.g. 'myfunc2'?
Sean de Wolski
Sean de Wolski 2015 年 1 月 15 日
fmincon(@myfunc2,etc.)

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by