ERROR: FMINCON requires all values returned by functions to be of data type double.
20 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Chen
le 29 Mar 2020
Réponse apportée : Ameer Hamza
le 29 Mar 2020
I have this function evalQ_test:
function Q = evalQ_test(x)
%%%
%%% Q_1 = x(1)+x(2);
%%%
Q=double(-(Q_1+Q_2+Q_3));
end
I omitted most of what the real content of the function here by %%%.
I have this objective function:
function [f, g, H] = evalQ_1(x)
% Calculate objective f
f = @(x) evalQ_test(x);
if nargout > 1 % gradient required
g = [f([x(1)+delta;x(2)])-f([x(1);x(2)]);f([x(1);x(2)+delta])-f([x(1);x(2)])];
if nargout > 2 % Hessian required
H = [x(1),0;0,x(2)];
end
end
And Hessian function:
function Hout = hessianfcn(x,lambda)
delta = 10^(-6);
% Hessian of objective
H = [x(1),0;0,x(2)];
% Hessian of nonlinear inequality constraint
Hg = 2*eye(2);
Hout = H + lambda.ineqnonlin*Hg;
Suppose the gradient and hessian are calaulated correctly here.
Then I run:
fun = @evalQ_1;
x0 = [1;1];
options = optimoptions('fmincon','Algorithm','interior-point',...
'SpecifyObjectiveGradient',true,'SpecifyConstraintGradient',true,...
'HessianFcn',@hessianfcn);
[x,fval,exitflag,output] = fmincon(fun,x0,[],[],[],[],[],[],[],options);
However, I have the error:
"Error using fmincon (line 694)
FMINCON requires all values returned by functions to be of data type double."
Is it because I am using a nested objective function? Or anything else?
Thanks in advance!!
0 commentaires
Réponse acceptée
Ameer Hamza
le 29 Mar 2020
Your objective function evalQ_1 is returning a function handle
f = @(x) evalQ_test(x);
whereas fmincon expect the first output to be a numeric value. Try something like this
function [f_, g, H] = evalQ_1(x)
% Calculate objective f
f = @(x) evalQ_test(x);
f_ = f(x);
if nargout > 1 % gradient required
g = [f([x(1)+delta;x(2)])-f([x(1);x(2)]);f([x(1);x(2)+delta])-f([x(1);x(2)])];
if nargout > 2 % Hessian required
H = [x(1),0;0,x(2)];
end
end
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Solver Outputs and Iterative Display dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!