要测试函数句柄,例如在你的问题中筛选出伪造的x = @ notreallyafunction,你可以使用
functions命令检查句柄并获取引用函数的名称,类型(简单,嵌套,重载,匿名等),和位置,如果它在文件中定义.
>> x = @notreallyafunction;
>> functions(x)
ans =
function: 'notreallyafunction'
type: 'simple'
file: ''
>> x = @(y) y;
>> functions(x)
ans =
function: '@(y)y'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>>
内置句柄的函数输出(例如x = @ round)看起来就像一个伪造的函数句柄(类型是’简单’).下一步是测试存在的命名函数:
>> x = @round;
>> fx = functions(x)
fx =
function: 'round'
type: 'simple'
file: ''
>> exist(fx.function)
ans =
5
>> x = @notreallyafunction;
>> fx = functions(x)
fx =
function: 'notreallyafunction'
type: 'simple'
file: ''
>> exist(fx.function)
ans =
0
但是,您需要处理匿名函数,因为它们无法存在测试:
>> x = @(y) y;
>> fx = functions(x)
>> exist(fx.function)
ans =
0
解决方案是首先检查类型.如果type是’anonymous’,则检查通过.如果类型不是“匿名”,则可以依靠exist来检查函数的有效性.总结一下,你可以创建一个这样的函数:
% isvalidhandle.m Test function handle for a validity.
% For example,
% h = @sum; isvalidhandle(h) % returns true for simple builtin
% h = @fake; isvalidhandle(h) % returns false for fake simple
% h = @isvalidhandle; isvalidhandle(h) % returns true for file-based
% h = @(x)x; isvalidhandle(h) % returns true for anonymous function
% h = 'round'; isvalidhandle(h) % returns true for real function name
% Notes: The logic is configured to be readable, not compact.
% If a string refers to an anonymous fnc, it will fail, use handles.
function isvalid = isvalidhandle(h)
if ~(isa(h,'function_handle') || ischar(h)),
isvalid = false;
return;
end
if ischar(h)
if any(exist(h) == [2 3 5 6]),
isvalid = true;
return;
else
isvalid = false;
return;
end
end
fh = functions(h);
if strcmpi(fh.type,'anonymous'),
isvalid = true;
return;
end
if any(exist(fh.function) == [2 3 5 6])
isvalid = true;
else
isvalid = false;
end