問題描述
如果這個變量在調用之間發生了變化,為什麼匿名函數的固定參數沒有更新? (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 在兩個函數調用之間發生了變化,它是 not 更新的,正如您在終端輸出中看到的那樣。這是預期的行為,還是錯誤?如果是前者,我該怎麼做才能強制
var2
在 objFunModel
內更新?重新定義匿名函數?
參考解法
方法 1:
When you create an anonymous function, the variables that are not in the parenthesis following the @ (var2
and nhi
in your example), are passed by value, not by reference. Thus, MATLAB has no way of knowing that the variable changed.
參考文件