Main Content

Obtain Generated Function Details

This example shows how to find the values of extra parameters in functions generated by prob2struct.

Create a nonlinear problem and convert the problem to a structure using prob2struct. Name the generated objective function and nonlinear constraint function.

x = optimvar('x',2);
fun = 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
prob = optimproblem('Objective',fun);
mycon = dot(x,x) <= 4;
prob.Constraints.mycon = mycon;
x0.x = [-1;1.5];
problem = prob2struct(prob,x0,'ObjectiveFunctionName','rosenbrock',...

Examine the first line of the generated constraint function circle2.

type circle2
function [cineq, ceq, cineqGrad, ceqGrad] = circle2(inputVariables, extraParams)
%circle2 Compute constraint values and gradients
%   [CINEQ, CEQ] = circle2(INPUTVARIABLES, EXTRAPARAMS) computes the
%   inequality constraint values CINEQ and the equality constraint values
%   CEQ at the point INPUTVARIABLES, using the extra parameters in
%   EXTRAPARAMS) additionally computes the inequality constraint gradient
%   values CINEQGRAD and the equality constraint gradient values CEQGRAD
%   at the current point.
%   Auto-generated by prob2struct on 23-Feb-2021 17:05:32

%% Compute inequality constraints.
Hineq = extraParams{1};
fineq = extraParams{2};
rhsineq = extraParams{3};
Hineqmvec = Hineq*inputVariables(:);
cineq = 0.5*dot(inputVariables(:), Hineqmvec) + dot(fineq, inputVariables(:)) + rhsineq;

%% Compute equality constraints.
ceq = [];

%% Compute constraint gradients.
% To call the gradient code, notify the solver by setting the
% SpecifyConstraintGradient option to true.
if nargout > 2
    cineqGrad = Hineqmvec + fineq;
    ceqGrad = [];


The circle2 function has a second input named extraParams. To find the values of this input, use the functions function on the function handle stored in problem.nonlcon.

F = functions(problem.nonlcon)
F = struct with fields:
            function: '@(x)circle2(x,extraParams)'
                type: 'anonymous'
                file: '/mathworks/devel/bat/Bdoc21a/build/matlab/toolbox/optim/problemdef/+optim/+internal/+problemdef/+compile/compileQuadraticConstraints.p'
           workspace: {[1x1 struct]}
    within_file_path: ''

To access the extra parameters, view the workspace field of F.

ws = F.workspace
ws = 1x1 cell array
    {1x1 struct}

Continue to extract the information at deeper levels until you see all the extra parameters.

ws1 = ws{1}
ws1 = struct with fields:
    extraParams: {[2x2 double]  [2x1 double]  [-4]}

ep = ws1.extraParams
ep=1×3 cell array
    {2x2 double}    {2x1 double}    {[-4]}

ans = 
   (1,1)        2
   (2,2)        2

ans = 
   All zero sparse: 2x1

ans = -4

Now you can read the circle2 file listing and understand what all of the variables mean.

Hineq = 2*speye(2);
fineq = sparse([0;0]);
rhsineq = -4;

See Also

Related Topics