Main Content

How to Use All Types of Constraints

This section contains an example of a nonlinear minimization problem with all possible types of constraints. This example does not use gradients.

The problem has five variables, x(1) through x(5). The objective function is a polynomial in the variables.

f(x)=6x2x5+7x1x3+3x22.

The objective function is in the local function myobj(x), which is nested inside the function fullexample. The code for fullexample appears at the end of this section.

The nonlinear constraints are likewise polynomial expressions.

x1-0.2x2x571

0.9x3-x4267

3x22x5+3x12x3=20.875.

The nonlinear constraints are in the local function myconstr(x), which is nested inside the function fullexample.

There are bounds on x3 and x5.

0x320, x51.

There is a linear equality constraint x1=0.3x2, which you can write as x1-0.3x2=0.

There are three linear inequality constraints:

0.1x5x4

x40.5x5

0.9x5x3.

Represent the bounds and linear constraints as matrices and vectors. The code that creates these arrays is in the fullexample function. As described in the fmincon Input Arguments section, the lb and ub vectors represent the constraints

lb x ub

The matrix A and vector b represent the linear inequality constraints

A*x b,

and the matrix Aeq and vector beq represent the linear equality constraints

Aeq*x = b.

Call fullexample to solve the minimization problem subject to all types of constraints.

[x,fval,exitflag] = fullexample
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 = 5×1

    0.6114
    2.0380
    1.3948
    0.1572
    1.5498

fval = 37.3806
exitflag = 1

The exit flag value of 1 indicates that fmincon converges to a local minimum that satisfies all of the constraints.

This code creates the fullexample function, which contains the nested functions myobj and myconstr.

function [x,fval,exitflag] = fullexample
x0 = [1; 4; 5; 2; 5];
lb = [-Inf; -Inf;  0; -Inf;   1];
ub = [ Inf;  Inf; 20; Inf; Inf];
Aeq = [1 -0.3 0 0 0];
beq = 0;
A = [0 0  0 -1  0.1
     0 0  0  1 -0.5
     0 0 -1  0  0.9];
b = [0; 0; 0];
opts = optimoptions(@fmincon,'Algorithm','sqp');
     
[x,fval,exitflag] = fmincon(@myobj,x0,A,b,Aeq,beq,lb,ub,...
                                  @myconstr,opts);

%---------------------------------------------------------
function f = myobj(x)

f = 6*x(2)*x(5) + 7*x(1)*x(3) + 3*x(2)^2;
end

%---------------------------------------------------------
function [c, ceq] = myconstr(x)

c = [x(1) - 0.2*x(2)*x(5) - 71
     0.9*x(3) - x(4)^2 - 67];
ceq = 3*x(2)^2*x(5) + 3*x(1)^2*x(3) - 20.875;
end
end

Related Topics