I'll put aside the arguments against both methods for a moment, although they are all very valid and a conscientious reader should try to understand them.
I can see two clear differences. For these examples we have to assume you've constructed the input string to the functions in your script, using some variable data, and assume it could be anything (by mistake or otherwise). So we prepare and account for the worst case.
str2func
includes some extra checks to make sure what you've passed is a valid function, which might avoid unwanted behaviour. Let's not take the stance of "yeah but you could do it this way to avoid that" and look at an example...
% Not assigning an output variable
% STR2FUNC: You've harmlessly assigned ans to some junk function
str2func('delete test.txt')
% EVAL: You've just deleted your super important document
eval('delete test.txt')
% Assigning an output variable
% STR2FUNC: You get a clear warning that this is not a valid function
f = str2func('delete test.txt')
% EVAL: You can a non-descript error "Unexpected MATLAB expression"
f = eval('delete test.txt')
Another difference is the subject of about half the str2func documentation. It concerns variable scopes, and is found under the heading "Examine Differences Between str2func
and eval
".
[Intro to the function]
If you use a character vector representation of an anonymous function, the resulting function handle does not have access to private or local functions.
[Examine Differences Between str2func
and eval
]
When str2func
is used with a character vector representing an anonymous function, it does not have access to the local function [...]. The eval
function does have access to the local function.
So to conclude, you might have use cases where each function is preferable depending on your desired error handling and variable scoping should never use eval
or str2func
wherever possible, as stated in the other answers.