如何验证函数句柄作为输入参数? [英] How can I validate a function handle as an input argument?
问题描述
我有一个具有函数句柄的类作为其properties
之一.
I have a class that has a function handle as one of its properties
.
classdef MyClass
properties
hfun %function handle
end
methods
function obj = Myclass(hfun,...)
%PROBLEM: validate that the input argument hfun is the right kind of function
if ~isa(hfun,'function_handle') || nargin(hfun)~=1 || nargout(hfun)~=1
error('hfun must be a function handle with 1 input and 1 output');
end
obj.hfun = hfun;
end
end
end
我想确保输入参数hfun
是具有1个输入和1个输出的函数句柄,否则它将出错.如果我可以更具体一些,我希望此函数将Nx3数组作为输入参数,并返回Nx3数组作为输出参数.
I'd like to make sure that the input argument hfun
is a function handle with 1 input and 1 output, otherwise it should error. If I could get even more specific I'd like this function to take an Nx3 array as an input argument and return an Nx3 array as the output argument.
以上代码适用于f = @sqrt
之类的内置函数,但是如果我尝试放入诸如f = @(x) x^(0.5)
之类的匿名函数,则nargout(hfun)
为-1,因为它将匿名函数视为[varargout] = f(x)
.此外,如果将句柄输入到f = @obj.methodFun
之类的类方法,则它将把函数转换为[varargout] = f(varargin)
形式,对于nargin
和nargout
都返回-1.
The above code works for built-in functions like f = @sqrt
but if I try to put in an anonymous function like f = @(x) x^(0.5)
, then nargout(hfun)
is -1 because it treats anonymous functions as [varargout] = f(x)
. Furthermore if you input the handle to a class method like f = @obj.methodFun
, then it converts the function to the form [varargout] = f(varargin)
which returns -1 for both nargin
and nargout
.
有人能找到一种简便的方法来验证函数句柄作为输入参数吗?与它来自哪种函数无关?
Has anyone figured out a convenient way to validate a function handle as an input argument? Independent of what kind of function handle it's from?
推荐答案
最接近验证函数句柄的输入和输出的地方是try/catch语句.
The closest I've come to validating the inputs and outputs of a function handle is inside a try/catch statement.
function bool = validateFunctionHandle(fn)
%pass an example input into the function
in = blahBlah; %exampleInput
try
out = fn(in);
catch err
err
bool = false;
return;
end
%check the output argument
if size(out)==correctSize and class(out)==correctType
bool=true;
else
bool=false;
end
end
这篇关于如何验证函数句柄作为输入参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!