%% Nonlinear Equality and Inequality Constraints
% 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.
%% Nonlinear Constraints
% 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.
%% Objective Function
% Solve the problem
%  \[\mathop {\min }\limits_x f(x) = {e^{{x_1}}}\left( {4x_1^2 + 2x_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 Problem
% 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)

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

[c,ceq] = confuneq(x)

% c is less than 0, as required. ceq is equal to 0 within the default constraint tolerance of 1e-6.
%
%% Helper Functions
% 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

% Copyright 2019 The MathWorks, Inc.