1

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?

1
  • 2
    It’s intended behavior. Commented Aug 30, 2019 at 14:13

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the clarification. So I'll use objFun = @(var1, var2) objFunModel(var1, var2, nhi) to define the anonymous function instead, and call it as objFun(var1_initial, var2). When needed in an optimization, I'll use @(var1) objFun(var1, var2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.