Developing an optimization script, I realized Matlab does not handle secondary arguments of anonymous functions as I expected.
Consider this simple 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
Though var2 is changed between both function calls, it is not updated as you can see in the terminal output.
Is this the intended behavior, or a bug?
In case of the former, what can I do to force var2 to be updated inside objFunModel? Define the anonymous function again?