You can include nonlinear constraints by writing a function that computes both equality and inequality constraint values. A nonlinear constraint function has the syntax
[c,ceq] = nonlinconstr(x)
c(x) represents the constraint
<= 0. The function
ceq(x) = 0.
You must have the nonlinear constraint function return both
For example, if you have the nonlinear equality constraint and the nonlinear inequality constraint x1x2 ≥ –10, rewrite them as
and then solve the problem using the following steps.
function f = objfun(x) f = exp(x(1))*(4*x(1)^2+2*x(2)^2+4*x(1)*x(2)+2*x(2)+1);
function [c,ceq] = confuneq(x) % Nonlinear inequality constraints c = -x(1)*x(2) - 10; % Nonlinear equality constraints ceq = x(1)^2 + x(2) - 1;
x0 = [-1,1]; % Make a starting guess at the solution options = optimoptions(@fmincon,'Algorithm','sqp'); [x,fval] = fmincon(@objfun,x0,,,,,,,... @confuneq,options);
After 21 function evaluations, the solution produced is
x,fval x = -0.7529 0.4332 fval = 1.5093 [c,ceq] = confuneq(x) % Check the constraint values at x c = -9.6739 ceq = 5.3291e-15
ceq is equal to 0 within the default
tolerance on the constraints of
1.0e-006 and that
less than or equal to 0, as desired.