Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a function handle as an input argument?

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

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.

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?

like image 815
joshkarges Avatar asked Sep 13 '25 18:09

joshkarges


1 Answers

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
like image 59
joshkarges Avatar answered Sep 15 '25 11:09

joshkarges