fileList = {@file1 @file2 @file3}; % A cell array of function handles
for iFile = 1:numel(fileList)
fileList{iFile}(); % Evaluate the function handle
pause % Wait for a keypress to continue
end
Run Code Online (Sandbox Code Playgroud)
您可以使用其上面的句柄或使用函数FEVAL来调用函数.如果字符串中有函数名,则可以使用函数STR2FUNC将其转换为函数句柄(假设它不是嵌套函数,需要函数句柄构造函数@
).以下示例说明了以下每个备选方案:
fileList = {str2func('file1') str2func('file2') str2func('file3')};
for iFile = 1:numel(fileList)
feval(fileList{iFile}); % Evaluate the function handle
pause % Wait for a keypress to continue
end
Run Code Online (Sandbox Code Playgroud)
您可能想知道我的答案(使用函数句柄)和Amro(使用字符串)之间的区别.对于非常简单的情况,您可能会看到没有区别.但是,如果对函数名使用字符串并使用EVAL对其进行评估,则可能会遇到更复杂的作用域和函数优先级问题.这是一个例子来说明......
假设我们有两个m文件:
fcnA.m
function fcnA
disp('I am an m-file!');
end
Run Code Online (Sandbox Code Playgroud)
fcnB.m
function fcnB(inFcn)
switch class(inFcn) % Check the data type of inFcn...
case 'char' % ...and do this if it is a string...
eval(inFcn);
case 'function_handle' % ...or this if it is a function handle
inFcn();
end
end
function fcnA % A subfunction in fcnB.m
disp('I am a subfunction!');
end
Run Code Online (Sandbox Code Playgroud)
该函数fcnB
旨在获取函数名称或函数句柄并对其进行评估.由于一个不幸的巧合(或者可能是故意的),fcnB.m中也存在一个也被称为子函数fcnA
.当我们fcnB
以两种不同的方式打电话会发生什么?
>> fcnB('fcnA') % Pass a string with the function name
I am a subfunction!
>> fcnB(@fcnA) % Pass a function handle
I am an m-file!
Run Code Online (Sandbox Code Playgroud)
请注意,将函数名称作为字符串传递会导致计算子函数fcnA
.这是因为在调用EVAL时,子函数fcnA
具有所有命名函数的最高函数优先级fcnA
.相反,传递函数句柄会导致fcnA
调用m文件.这是因为首先创建函数句柄,然后fcnB
作为参数传递给它.m文件fcnA
是范围内唯一的文件(即唯一可以调用的文件)fcnB
,因此是函数句柄所依赖的文件.
一般来说,我更喜欢使用函数句柄,因为我觉得它让我可以更好地控制调用哪个特定函数,从而避免出现意外行为,如上例所示.