TL;DR - eval
has access to locally defined functions while str2func
does not. The "right" function to use among these two depends on the structure of your code.
Without getting into the whole "why eval
is bad" discussion, I shall try to focus on the relevant piece of MATLAB documentation that discusses it in the context of your question:
Consider a file with two functions:
function out = q46213509
f='a^x+exp(b)+sin(c*x)+d';
fHandle = {eval(['@(x, a, b, c, d) ' f]), str2func(['@(x, a, b, c, d) ' f])};
out = [fHandle{1}(1,2,3,4,5) fHandle{2}(1,2,3,4,5)];
end
function e = exp(x)
e = x.^0./factorial(0) - x.^1./factorial(1) + x.^2./factorial(2); % Error is deliberate
end
When you run the above, it results in :
ans =
8.7432 26.3287
If you're working with classes and you define your own operators this might get out of hand... Let's say somebody decided to add a file to your MATLAB path, and conveniently give it the name of some function you use, or that of an overloadable operator (i.e. mpower.m
):
function out = mpower(varargin)
% This function disregards all inputs and prints info about the calling workspace.
disp(struct2cell(evalin('caller','whos')));
end
While in some cases, MATLAB protects from redefinition of builtin functions, I bet the scenario above might confuse str2func
quite a lot...