Failure in initial objective function evaluation. FMINUNC cannot continue. Need some help

6 views (last 30 days)
It's my first time to use fminunc solver. R_pq,array_x,array_y,M,N,R00 are constants I have set.
x0 = -pi + (pi+pi)*rand(M,N);
options = optimoptions(@fminunc,'Algorithm','trust-region','SpecifyObjectiveGradient',true);
[x,fval,output]=fminunc(@(x) error_fun(x,R_pq,array_x,array_y,M,N,R00),x0,options);
Without options, the code can function without error. But after I set the options, it shows
Error using error_fun
Too many output arguments.
Error in main_beamshaping_336_XZLZ_AMM_phaseonly>@(x)error_fun(x,R_pq,array_x,array_y,M,N,R00)
(line 128)
[x,fval,output]=fminunc(@(x) error_fun(x,R_pq,array_x,array_y,M,N,R00),x0,options);
Error in fminunc (line 303)
[f,GRAD] = feval(funfcn{3},x,varargin{:});
Error in main_beamshaping_336_XZLZ_AMM_phaseonly (line 128)
[x,fval,output]=fminunc(@(x) error_fun(x,R_pq,array_x,array_y,M,N,R00),x0,options);
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
I am confused about what is wrong. I would be very grateful indeed for any help

Answers (2)

Matt J
Matt J on 22 Sep 2020
Edited: Matt J on 22 Sep 2020
You have set SpecifyObjectiveGradient=true, but your objective function code does not provide a second output for your gradient calculation.

Walter Roberson
Walter Roberson on 22 Sep 2020
When you have the option SpecifyObjectiveGradient, then your function must be able to return the gradient as well as the objective value. It should check nargout and only set the second output if nargout > 1
When you use that option, your nonlinear constraint function (if any) should have two extra outputs. See https://www.mathworks.com/help/optim/ug/nonlinear-constraints.html#bskkri8 "Including Gradients in Constraint Functions"

Tags

Community Treasure Hunt

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

Start Hunting!