5
是否可以将以下代码替换为不使用异常的东西?手柄x
是一个提供的手柄。我想在使用前测试它的有效性(有实际的代码来支持句柄)。是否可以在没有尝试块的情况下测试函数句柄?
x = @notreallyafunction;
try
x();
catch
disp('Sorry function does not exist.');
end
是否可以将以下代码替换为不使用异常的东西?手柄x
是一个提供的手柄。我想在使用前测试它的有效性(有实际的代码来支持句柄)。是否可以在没有尝试块的情况下测试函数句柄?
x = @notreallyafunction;
try
x();
catch
disp('Sorry function does not exist.');
end
要测试功能处理,如筛选出你的问题的虚假[email protected]
,则可以使用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]}
>>
functions
的一个手柄的输出到一个内建(例如[email protected]
)将看起来就像一个假的功能句柄(type
是'simple'
)。下一步是测试在命名的功能是否存在:
>> 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
。如果type
是'anonymous'
,则检查通过。如果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
不,这是不正确的。它返回true。我检查了*功能,但没有发现任何有用的东西。 – Andrej
新的答案。我第一次错过了这一点。 – chappjc
嗯,仍然不起作用... y = @总和;函数(x)返回与函数(y)相同的结果...您无法区分 – Andrej