modify anonymous function using eval
9 views (last 30 days)
Show older comments
i have a question regarding the use of eval.
lets say i have an anonymous function:
fun1 = @(x, p1, p2, p3) x*p1*p2*p3;
which uses the parameters p1, p2, p3 as the multiplicators. iow i want to modify this anonymous function so that p1, p2, p3 are fixed to some values. I would do this by:
p1 = 1;
p2 = 1;
p3 = 2;
% fun2 = @(x) fun1(x*p1*p2*p3);
% edited:
fun2 = @(x) fun1(x,p1,p2,p3);
now i want to make it so that the decision variables and fixed parameters can be set by 2 arrays. these are given by previous steps.
decVars = {'x'};
fixPars = {'p1', 'p2', 'p3'};
fun3 = eval(sprintf('@( %s ) fun1( %s, %s )', strjoin(decVars, ', '), ...
strjoin(decVars, ', '), strjoin(fixPars,', ')));
i want to do this so that i can reduce the number of function inputs, which is required for further steps.
i know eval is deemed as evil, but i can not think of another way to do this. what do you recommend?
3 Comments
Answers (2)
Jan
on 2 Nov 2022
Edited: Jan
on 2 Nov 2022
Use a function instead:
function y = fun1(x, p1, p2, p3)
if nargin == 1
p1 = 1;
p2 = 1;
p3 = 2;
end
y = x*p1*p2*p3;
end
Do you have a good reason to use a less powerful anonymous function? Deciding for a standard function offers more possibilities for free without ugly eval constructions.
Note that eval dynamically creates entries in the lookuop table of functions or variables. This impedes the JIT acceleration and can slowdown the processing by a factor of 100 - even in parts of the code, which do not use the eval'ed anonymous function.
2 Comments
Jan
on 3 Nov 2022
I prefer clean and clear code for productive work and avoid meta-programming by eval for good reasons.
I would not even store function handles in MAT files, if I can use functions as M-files instead. If you import a function dynamically from a MAT file, you cause exactly the same effect as using EVAL.
Stephen23
on 2 Nov 2022
I assume that you want to select from a larger set of different parameters. In that case, put them all into one cell array and then use indexing to select which ones the function is called with:
prm = { 13, 18, 23, 64, 99}; % all possible parameters
idx = [false,true,true,false,true] % corresponding indices (logical or linear)
fun1(x, prm{idx})
0 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!