Including gradients and hessians for fmincon

18 views
Skip to first unread message

Ali_E

unread,
Sep 7, 2019, 9:24:33 AM9/7/19
to YALMIP
Hello professor! I wanted to include gradient of functions for FMINCON, but after running I got:

"Gradient of nonlinear inequality constraints must have size 4-by-12."

here is my main code and objective functions:

clc;
clear
;
close all
;
%% Problem Definition
nVar
=4;
VarSize=[1 nVar];
VarMin=10^(-3);
VarMax=10^2;
%% Weighted-Sum Approach
FWS
=@(x) MyCost(x);
x0
=unifrnd(VarMin,VarMax,VarSize);
x0
=x0';
A=[];
b=[];
LB=[10^(-3);10^(-3);10^(-3);10^(-3)];
UB=[10^2;10^2;10^2;10^2];
nonlcon = @NLC2;
options=optimoptions('
fmincon','Display','iter','Algorithm','interior-point','SpecifyConstraintGradient',true,'TolFun',10^(-12),'TolCon',10^(-10),'MaxFunEvals',4*10^3);
[x,fval,exitflag,output,lambda,grad,hessian]=fmincon(FWS,x0,A,b,[],[],LB,UB,nonlcon,options);

function z = Obj1(x)
yref
= 0;
p1
= -6.2039e-06;
p2
= 0.012729;
p3
= -0.040506;
p4
= -0.035217;
p5
= 0.28562;
p6
= -0.3329;
p7
= -0.19587;
p8
= 0.75971;
p9
= -0.54118;
p10
= -0.021845;
p11
= 0.098187;
mu
= 50.5;
sigma
= 29.011;
n
=2;
g
= (x(1:n-1)-mu)/sigma;
z
= sum(((yref-(p1*g.^10+p2*g.^9+p3*g.^8+p4*g.^7+p5*g.^6+p6*g.^5+p7*g.^4+p8*g.^3+p9*g.^2+p10*g+p11)).^2));
end

function z = Obj2(x)
yref
= 0;
p1
= -0.0053913;
p2
= 0.011457;
p3
= 0.039991;
p4
= -0.1433;
p5
= 0.070996;
p6
= 0.31844;
p7
= -0.64456;
p8
= 0.33539;
p9
= 0.30767;
p10
= -0.37571;
p11
= 0.071788;
mu
= 50.5;
sigma
= 29.011;
n
=2;
g
= (x(1:n-1)-mu)/sigma;
z
= sum(((yref-(p1*g.^10+p2*g.^9+p3*g.^8+p4*g.^7+p5*g.^6+p6*g.^5+p7*g.^4+p8*g.^3+p9*g.^2+p10*g+p11)).^2));
end


function z = MyCost(x)
K
=3;
s
=zeros(1,K);
for i=1:K
s
(i) = (10^(K-i))*2;
end
S
= diag(s);
M
=60;
w1
=linspace(0,1,M);
w2
=1-w1;
for j=1:M
z1
= w1(j)*Obj1(x);
z2
= w2(j)*Obj2(x);
end
n
=2;
z
= z1+z2+x(n:end)'*S*x(n:end);
end


function [c,ceq,gradc,gradceq]=NLC2(x)
n
=2;
c
=[Obj1(x)-x(n:end);-x(n:end);
   
Obj2(x)-x(n:end);-x(n:end)];
ceq
=[];
if nargout>1
gradc
=[gradient(Obj1(x)-x(n:end),x);gradient(-x(n:end),x);
       gradient
(Obj2(x)-x(n:end),x);gradient(-x(n:end),x)];
gradceq
=[];
end
end


Johan Löfberg

unread,
Sep 7, 2019, 1:15:19 PM9/7/19
to YALMIP
This is a support forum for YALMIP, not matlab in general.

The error message is telling you load and clear what is wrong, hence debug the code to see why you are returning something else
Reply all
Reply to author
Forward
0 new messages