Main Content

生成された関数詳細の取得

この例では、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 12-Feb-2024 22:17:26

%% 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 という名前の 2 番目の入力があります。この入力の値を見つけるには、problem.nonlcon に保存された関数ハンドルに対して functions 関数を使用します。

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

追加のパラメーターにアクセスするには、Fworkspace フィールドを表示します。

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

すべての追加のパラメーターが表示されるまで、情報の抽出レベルをより詳細にしていきます。

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

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

ep{1}
ans = 
   (1,1)        2
   (2,2)        2

ep{2}
ans = 
   All zero sparse: 2x1

ep{3}
ans = -4

これで、circle2 ファイル リストを読み取って、すべての変数の意味を理解できるようになります。

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

参考

関連するトピック