Main Content

This example shows how to solve an optimization problem containing nonlinear constraints. 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)`

The function `c(x)`

represents the constraint `c(x) <= 0`

. The function `ceq(x)`

represents the constraint `ceq(x) = 0`

.

**Note:** You must have the nonlinear constraint function return both `c(x)`

and `ceq(x)`

, even if you have only one type of nonlinear constraint. If a constraint does not exist, have the function return `[]`

for that constraint.

Suppose that your nonlinear equality constraint is

$${x}_{1}^{2}+{x}_{2}=1$$

and your nonlinear inequality constraint is

$${x}_{1}{x}_{2}\ge -10$$.

Rewrite these constraints as

$$\begin{array}{c}{x}_{1}^{2}+{x}_{2}-1=0\\ -{x}_{1}{x}_{2}-10\le 0.\end{array}$$

The `confuneq`

function at the end of this example implements these inequalities in the correct syntax.

Solve the problem

$$\underset{x}{\mathrm{min}}f(x)={e}^{{x}_{1}}\left(4{x}_{1}^{2}+2{x}_{2}^{2}+4{x}_{1}{x}_{2}+2{x}_{2}+1\right)$$

subject to the constraints. The `objfun`

function at the end of this example implements this objective function.

Solve the problem by calling the `fmincon`

solver. This solver requires an initial point; use the point `x0 = [-1,-1]`

.

x0 = [-1,-1];

There are no bounds or linear constraints in the problem, so set those inputs to `[]`

.

A = []; b = []; Aeq = []; beq = []; lb = []; ub = [];

Call the solver.

[x,fval] = fmincon(@objfun,x0,A,b,Aeq,beq,lb,ub,@confuneq)

Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.

`x = `*1×2*
-0.7529 0.4332

fval = 1.5093

The solver reports that the constraints are satisfied at the solution. Check the nonlinear constraints at the solution.

[c,ceq] = confuneq(x)

c = -9.6739

ceq = 2.0668e-12

`c`

is less than 0, as required. `ceq`

is equal to 0 within the default constraint tolerance of `1e-6`

.

The following code creates the `confuneq`

function.

function [c,ceq] = confuneq(x) % Nonlinear inequality constraints c = -x(1)*x(2) - 10; % Nonlinear equality constraints ceq = x(1)^2 + x(2) - 1; end

The following code creates the `objfun`

function.

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); end