Correct way to test if a value is a function?
조회 수: 58 (최근 30일)
이전 댓글 표시
I'm using the following test to check if a value is a function (standard or anonymous):
if isa(value, 'function_handle')
disp('Yeah bro');
else
disp('Nah bro');
end
This satisfies me for everything I've thrown at it so far, and it's pleasing to have code that speaks my regional dialect... I just wanted to check that this is the accepted way to do it in MatLab.
I didn't see an equivalent function (as there is for ischar, iscell and the like) but that could be because it's not a very common thing to do.
Out of indulgent curiosity, is there a test to see if a function is anonymous or not? Forget about whether there's a real-world use case for it. I decided that this works:
if isa(value, 'function_handle')
if strncmp(char(value), '@', 1)
disp('Anonymous as, bro');
else
disp('Average as, bro');
end
end
Obviously all this could be wrapped up into helpful little bundles devoid of Kiwi dialect...
isfun = @(f) isa(f, 'function_handle');
isstdfun = @(f) isfun(f) && ~strncmp(char(f), '@', 1);
isanonfun = @(f) isfun(f) && strncmp(char(f), '@', 1);
Anyone able to make this more concise? And is there an official word to describe functions declared with the function keyword? I kinda thought 'explicit' would suit.
Cheers =)
댓글 수: 6
per isakson
2012년 5월 4일
I would replace char(f) by func2str(f), because it communicates the intent better. And the test strncmp(char(f), '@', 1) by strncmp( func2str(f), '@(', 2), because every(?) "string of a function_handle" starts with a "@".
답변 (2개)
Sean de Wolski
2012년 5월 4일
To test if a function is defined in a file with the keyword function, test the output of exist().
v = exist('some_script') %v = 1;
v = exist('some_function') %v = 2
댓글 수: 3
Sean de Wolski
2012년 5월 8일
Hi Geoff, This was just to answer the last question in your question suite:
"And is there an official word to describe functions declared with the function keyword? I kinda thought 'explicit' would suit"
Steven Lord
2024년 12월 20일
If you are debugging (note: don't use this in "production" code, as called out in the Note on its documentation page) you could use the functions function to determine if a variable is a function handle or not.
f = @sin; % "named" or "simple" function handle
check1 = isa(f, 'function_handle')
info1 = functions(f)
g = @(x) sin(x); % anonymous function
check2 = isa(g, 'function_handle')
info2 = functions(g)
If the variable you pass into functions isn't a function handle, it will throw an error.
notFunctionHandle = 1:10;
functions(notFunctionHandle)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!