I already showed that the performance of str2func
is better, but I got a lot of comments stating that there are more fundamental reasons to not use eval
. Which fundamental reasons do apply to eval
and do not apply to str2func
in the following situation:
f='a^x+exp(b)+sin(c*x)+d'
eval
:y = eval(f)
or (suggested by rahnema1)
fHandle = eval(['@(x, a, b, c, d) ' f]); y = fHandle(x, a, b, c, d);
str2func
:fHandle = str2func(['@(x, a, b, c, d) ' f]); y = fHandle(x, a, b, c, d);
Why is the first option worse than the second one except for performance reasons?
Remarks
Note that I'm aware that it is good practice to avoid both methods if possible.
Note that I assign the output of
eval
to a variable, which avoids a lot of tricky code from being executed.