主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

获取生成函数详细信息

此示例显示如何在 prob2struct 生成的函数中查找额外参数的值。

创建一个非线性问题,并使用 prob2struct 将该问题转换为结构体。将生成的目标函数和非线性约束函数命名为。

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',...
    'ConstraintFunctionName','circle2');

检查生成的约束函数 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.
%
%   [CINEQ, CEQ, CINEQGRAD, CEQGRAD] = circle2(INPUTVARIABLES,
%   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 01-Feb-2025 13:09:34

%% 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 = [];

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

circle2 函数有第二个输入名为 extraParams。要找到此输入的值,请对存储在 problem.nonlcon 中的函数句柄使用 functions函数。

F = functions(problem.nonlcon)
F = struct with fields:
            function: '@(x)fun(x,extraParams)'
                type: 'anonymous'
                file: '/mathworks/devel/bat/filer/batfs2566-0/Bdoc25a.2864802/build/runnable/matlab/toolbox/shared/adlib/+optim/+internal/+problemdef/+compile/snapExtraParams.p'
    within_file_path: ''
           workspace: {[1×1 struct]}

要访问额外参数,请查看 workspaceF 字段。

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

继续在更深的层次上提取信息,直到看到所有额外的参数。

ws1 = ws{1}
ws1 = struct with fields:
            fun: @circle2
    extraParams: {[2×2 double]  [2×1 double]  [-4]}

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

ep{1}
ans = 2×2 sparse double matrix (2 nonzeros)
   (1,1)        2
   (2,2)        2

ep{2}
ans = 2×1 sparse double column vector
   All zero

ep{3}
ans = 
-4

现在您可以阅读 circle2 文件列表并了解所有变量的含义。

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

另请参阅

主题