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