matlab的try函数,matlab – 是否可以在没有try块的情况下测试函数句柄?

要测试函数句柄,例如在你的问题中筛选出伪造的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值