%% Solve Nonlinear System of Equations, Problem-Based
% To solve the nonlinear system of equations
% \exp(-\exp(-(x_1+x_2))) = x_2\left (1 + x_1^2\right )\\
% x_1\cos(x_2) + x_2\sin(x_1) = \frac 1 2
% using the problem-based approach, first define x as a two-element optimization variable.

x = optimvar('x',2);

% Create the first equation as an optimization equality expression.

eq1 = exp(-exp(-(x(1) + x(2)))) == x(2)*(1 + x(1)^2);

% Similarly, create the second equation as an optimization equality expression.

eq2 = x(1)*cos(x(2)) + x(2)*sin(x(1)) == 1/2;

% Create an equation problem, and place the equations in the problem.

prob = eqnproblem;
prob.Equations.eq1 = eq1;
prob.Equations.eq2 = eq2;

% Review the problem.

show(prob)

% Solve the problem starting from the point [0,0]. For the problem-based approach, specify the initial point as a structure, with the variable names as the fields of the structure. For this problem, there is only one variable, x.

x0.x = [0 0];
[sol,fval,exitflag] = solve(prob,x0)

% View the solution point.

disp(sol.x)

%
%% Unsupported Functions Require fcn2optimexpr
% If your equation functions are not composed of elementary functions, you must convert the functions to optimization expressions using fcn2optimexpr. For the present example:

ls1 = fcn2optimexpr(@(x)exp(-exp(-(x(1)+x(2)))),x);
eq1 = ls1 == x(2)*(1 + x(1)^2);
ls2 = fcn2optimexpr(@(x)x(1)*cos(x(2))+x(2)*sin(x(1)),x);
eq2 = ls2 == 1/2;

% See Supported Operations on Optimization Variables and Expressions and Convert Nonlinear Function to Optimization Expression.
%
% Copyright 2019 The MathWorks, Inc.