modify anonymous function using eval
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Jan
2022-11-2
编辑:Jan
2022-11-2
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 个评论
Jan
2022-11-3
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
2022-11-2
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!