为什么匿名函数的固定参数没有更新,如果这个变量在调用之间发生了变化?

Why is fixed argument of anonymous function not updated, if this variable has changed between calls?

开发优化脚本,我发现 Matlab 没有像我预期的那样处理匿名函数的二次参数。

考虑这个简单的 MWE:

%% Define basic parameters
daysTotal       = 3;
hoursTotal      = daysTotal*24;
nhi             = 4;        % Third argument, does not change.
intervalsTotal  = hoursTotal*nhi;
q_in_mean       = 0.82;

% Original definition of var2
var2            = zeros(hoursTotal, 1);
var2(2:2:end)   = 1;        % Second argument, does change!

var1_initial = var2.*q_in_mean/12; % Initial version of first argument

%% Define anonymous function
objFun          = @(var1) objFunModel(var1, var2, nhi);

%% Call objFun for the first time
objFun(var1_initial); % Result of sum(var2) = 36, which is correct.

%% Change var2
var2            = zeros(hoursTotal, 1);
var2(4:4:end)   = 1;

%% Call objFun again
objFun(var1_initial); % Result of sum(var2) is still 36 inside objFunModel
sum(var2) % Actual value of sum(var2) = 18 after change!

%% Separate functions
function varStd = objFunModel(var1, var2, nhi)
    sum(var2)
    varRes  = cumsum(2*var1 - 0.12*var2);
    varStd  = std(varRes);
end

虽然 var2 在两个函数调用之间发生了变化,但它 没有 更新,正如您在终端输出中看到的那样。 这是预期的行为还是错误? 如果是前者,我该怎么做才能在 objFunModel 中强制更新 var2?重新定义匿名函数?

当您创建匿名函数时,不在 @ 后面括号中的变量(在您的示例中为 var2nhi)按值传递,而不是按引用传递。因此,MATLAB 无法知道变量发生了变化。