TL; DR - eval , str2func - . "" , , .
" eval ", MATLAB, :
:
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
, :
ans =
8.7432 26.3287
If you work with classes, and you define your own operators , this can get out of hand ... Let's say someone decided to add a file to the MATLAB path and conveniently give it the name of any function that you are using, or overloaded 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
Although in some cases MATLAB protects against overriding built-in functions, I'm sure the scenario described above can be a bit confusing str2func...
source
share