%% 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) = 6x_2 x_5 + 7x_1 x_3 + 3x_2^2.
% 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.
% x_1 - 0.2 x_2 x_5 \le 71
% 0.9 x_3 - x_4^2 \le 67
% 3x_2^2x_5 + 3x_1^2x_3 = 20.875.
% The nonlinear constraints are in the local function myconstr(x), which is nested inside the function fullexample.
% There are bounds on x_3 and x_5.
% 0\le x_3\le 20, x_5 \ge 1.
% There is a linear equality constraint x_1= 0.3x_2, which you can write as x_1 - 0.3 x_2= 0.
% There are three linear inequality constraints:
% 0.1 x_5 \le x_4
% x_4\le 0.5 x_5
% 0.9 x_5\le x_3.
% 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 \le x \le ub
% The matrix A and vector b represent the linear inequality constraints
% A*x \le 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

% 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

% Copyright 2019 The MathWorks, Inc.