%% Anonymous Nonlinear Constraint Functions
% Nonlinear constraint functions must return two outputs. The first output corresponds to nonlinear inequalities, and the second corresponds to nonlinear equalities.
% Anonymous functions return just one output. So how can you write an anonymous function as a nonlinear constraint?
% The deal function distributes multiple outputs. For example, suppose that you have the nonlinear inequalities
% \[\begin{array}{c}
% \frac{{x_1^2}}{9} + \frac{{x_2^2}}{4} \le 1,\\
% {x_2} \ge x_1^2 - 1.
% \end{array}\]
% Suppose that you have the nonlinear equality
% x_2 = \tanh(x_1).
% Write a nonlinear constraint function as follows.

c = @(x)[x(1)^2/9 + x(2)^2/4 - 1;
        x(1)^2 - x(2) - 1];
ceq = @(x)tanh(x(1)) - x(2);
nonlinfcn = @(x)deal(c(x),ceq(x));

% To minimize the function \cosh(x_1) + \sinh(x_2) subject to the constraints in nonlinfcn, use fmincon.

obj = @(x)cosh(x(1))+sinh(x(2));
opts = optimoptions(@fmincon,'Algorithm','sqp');
z = fmincon(obj,[0;0],[],[],[],[],[],[],nonlinfcn,opts)

% To check how well the resulting point z satisfies the constraints, use nonlinfcn.

[cout,ceqout] = nonlinfcn(z)

% z satisfies all the constraints to within the default value of the constraint tolerance ConstraintTolerance, 1e-6.
% For information on anonymous objective functions, see Anonymous Function Objectives.
% Copyright 2019 The MathWorks, Inc.