I have an array of anonymous functions (2x2 array, 4 functions, each with 2 variables, x1 and x2) and I want to evaluate all 4 functions at the points x1 and x2 without extracting them and doing them individually. Is there any way to do this?

specifically:
J = {@(x1) 8*x1 - 20, @(x2) x2/2; @(x2) x2/2 + 2, @(x1) 1/2*x1 - 5}
and I want this evaluated at say x1 = 1 and x2 = 2 and get something back that looks like
Jeval = [-12 1; 2 -4.5]

 Accepted Answer

No, there is no way to do that.
varnames = {'x1', 'x2'};
varvals = {x1, x2};
[tf, idx] = ismember(regexp(cellfun(@func2str, J, 'uniform', 0), '(?<=@\()\w+', 'match', 'once'), varnames);
if ~all(tf)
J(~tf)
error('Unknown anonymous variable names in above anonymous functions');
end
vars_to_pass = varvals(idx);
Jeval = cellfun(@(F, x) F(x), J, vars_to_pass);
Notice the amount of work that was required. When you code an anonymous function, the variable name you use is a "dummy parameter", standing in for the value you pass in at the corresponding position. Anonymous functions do not look into the calling environment to find a variable with a similar name and substitute the value from the calling environment; you need to pass in the value you need. Which, in your case, means that you have to parse the character version of the anonymous function to figure out which variable was mentioned.
It would have been easier if your code had been
J = {@(x1, x2) 8*x1 - 20, @(x1, x2) x2/2; @(x1, x2) x2/2 + 2, @(x1, x2) 1/2*x1 - 5}
because then all that would have been required would have been
cellfun(@(F) F(x1, x2), J)

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!