Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何将函数句柄验证为输入参数?_Matlab_Oop_Validation_Matlab Class_Function Handle - Fatal编程技术网

Matlab 如何将函数句柄验证为输入参数?

Matlab 如何将函数句柄验证为输入参数?,matlab,oop,validation,matlab-class,function-handle,Matlab,Oop,Validation,Matlab Class,Function Handle,我有一个类,它的属性之一是函数句柄 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 ~i

我有一个类,它的
属性之一是函数句柄

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数组作为输出参数

上面的代码适用于内置函数,如
f=@sqrt
,但是如果我尝试放入一个匿名函数,如
f=@(x)x^(0.5)
,那么
nargout(hfun)
是-1,因为它将匿名函数视为
[varargout]=f(x)
。此外,如果您向类方法(如
f=@obj.methodFun
)输入句柄,那么它会将函数转换为
[varargout]=f(varargin)
,对于
nargin
nargout
都返回-1


有没有人想出一种方便的方法来验证函数句柄作为输入参数?与函数句柄的类型无关?

您可以使用
来判断变量是否是函数句柄,但是没有简单的方法来验证输入和输出的类型,因为MATLAB是松散类型的,变量可以包含任何内容,只要它能够在运行时理解如何解释命令。正如Mohsen指出的,你也可以使用函数来获取更多信息,但这对你帮助不大

这是我认为你能得到的最接近的结果:

fn = @(x,y) x + x*2

if strcmpi(class(fn), 'function_handle')
    functionInfo = functions(fn)
    numInputs =  nargin(fn)
    numOutputs = nargout(fn)
end

如果速度不是问题,您可以创建一个类,其中包含运行函数的成员函数
run
,以及返回所需详细信息的
geInfo
。然后,您总是将一个类传递给函数,该函数将包含内置的信息。然而,这将是缓慢和不方便的

最接近验证函数句柄的输入和输出的是try/catch语句

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

您可以使用
函数
函数提取有关函数句柄的更多信息。它的实际用途是什么?我想用它做一些用途。我正在编写一个A*类,它计算节点边图上的最短路径,但我想让用户能够自定义启发式函数,而不仅仅是使用默认的欧几里德距离。另一个用途是在我的RRT类中,它实现了快速探索的随机树算法来构建节点边图。我想让用户能够自定义节点扩展上的运动约束。用户可以将此运动约束作为函数句柄输入。我可以使用
isa(fn,'function_handle')
来检测它是否是函数句柄,但是
nargin
nargout
是可变的,这取决于函数是否是内置的、类方法、匿名的等等。
函数(fn)
命令给出了名称、类型和文件,但没有说明任何关于输入/输出参数的内容。