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

人走茶凉 提交于 2019-12-04 12:25:15

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

You can use class to tell whether a variable is a function handle but there is no easy way to validate the type of input and output because MATLAB is loosely typed and a variable can contain anything so long as it can figure out how to interpret the commands at runtime. As Mohsen pointed out, you can also functions to get more info but it won't help you too much.

Here is the closest I think you can get:

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

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

If speed is not an issue, you could create a class with member functions run that runs the function and geInfo that returns whatever details you need. Then you always pass a class to you function that will have the info built into it. However, this will be slow and inconvenient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!