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
總結
以上是生活随笔為你收集整理的matlab的try函数,matlab – 是否可以在没有try块的情况下测试函数句柄?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线性分组码c语言实验报告,C语言线性分组
- 下一篇: mysql 查看运行级别_运行级别及进程