%% Solve Problem Using Both Approaches
% This example shows how to obtain most of the same information using either the problem-based approach or the solver-based approach. First create a problem and solve it using the problem based approach.

x = optimvar('x',3,1,'LowerBound',1,'UpperBound',1);
y = optimvar('y',3,3,'LowerBound',-1,'UpperBound',1);
prob = optimproblem('Objective',x'*y*x + [2 3 4]*x);
rng default
x0.x = rand(3, 1);
x0.y = rand(3, 3);
[solp,fvalp,exitflagp,outputp] = solve(prob,x0);

%
% Next, convert the problem to solver-based form using prob2struct. To have the fmincon solver use the automatic gradients in the problem, set the SpecifyObjectiveGradient option to true.

solverprob = prob2struct(prob,x0);
solverprob.options = optimoptions(solverprob.options,"SpecifyObjectiveGradient",true);

% Solve the problem using fmincon.

[sols,fvals,exitflags,outputs] = fmincon(solverprob);

%
% To convert the fmincon solution to the structure form returned by solve, create appropriate structures using varindex.

idx = varindex(prob);
sol.x = sols(idx.x);
sol.y = sols(idx.y);

% The y index that varindex uses is a linear index. Reshape the variable sol.y to have the size of x0.y.

sol.y = reshape(sol.y,size(x0.y));

% Check that the two solution structures are identical.

isequal(sol,solp)

%
% The reason that the two approaches are not completely equivalent is that fmincon can return more arguments such as Lagrange multipliers, whereas solve cannot.
% Copyright 2020 The MathWorks, Inc.