MATLAB Answers

0

Problem using 'deal' for objective and gradient in comb. with 'DerivativeCheck'

Sargondjani さんによって質問されました 2012 年 7 月 4 日
When using optimization tools I usually keep my objective function and gradient function as separate subfunctions and then use 'deal' to combine them as output of one function (see example 'f_opt' below).
This has always worked fine, but now that i try to run 'DerivativeCheck' it gives me an error:
??? Error using ==> deal at 38 The number of outputs should match the number of inputs.
I dont understand why matlab suddenly has problems understanding what i want. Can somebody explain why and give a solution?? (of course i can make subfunction instead of a handle, but say i wanted to keep my 'deal')
Here is an example program: x1 and x2 solve without problem, but x3 does not give a solution but the error.
function main_fun_grad();
f_opt=@(x)deal(fun_obj(x),fun_grad(x));
x0=1;
x1=fminunc(f_opt,x0,optimset('GradObj','on'))
x2=fminunc(@fun_all,1,optimset('GradObj','on','DerivativeCheck','on'))
x3=fminunc(f_opt,x0,optimset('GradObj','on','DerivativeCheck','on'))
end
%%auxiliary
function [f]=fun_obj(x)
f = x^2;
end
function [g]=fun_grad(x);
g=2*x;
end
function [f, g]=fun_all(x)
f = x^2;
g = 2*x;
end

  0 件のコメント

サインイン to comment.

1 件の回答

回答者: Richard Brown 2012 年 7 月 5 日
編集済み: Richard Brown 2012 年 7 月 5 日
 採用された回答

An internal routine (in this case finDiffEvalAndChkErr) is calling your routine with only one output. For a regular function that returns two outputs, this is fine, as you are allowed to do this (the second output gets ignored).
But for your function with deal, you are requiring it to always be called with two outputs, rather than optionally.
I suggest you just resign yourself to writing a wrapper function for your two routines (you can also save yourself evaluating the gradient too if it's not required).
function [f, g] = fun_all(x)
f = fun_obj(x);
if nargout == 2
g = fun_grad(x);
end
end

  3 件のコメント

Sargondjani 2012 年 7 月 5 日
aaaaah, ok. makes sense...
o, and you use the 'if nargout' only to reduce computation time, right?
Richard Brown 2012 年 7 月 5 日
Yes indeed. No point in computing the derivative if you don't need it!
Sargondjani 2012 年 7 月 5 日
thanks alot!! (forgot to mention that, haha)

サインイン to comment.



Translated by