1

I have a question concerning the validation of functions as input to other functions.

Suppose that I want to create a simple function that iterates another function 5 times on vector input x (what it does is not so important, it's just for illustration purposes):

% A function to iterate another function
function result = iterateFunction(funcHandle,x)

% Create an input parser to validate x
p = inputParser;
isValidX = @(x) validateattributes(x, {'numeric'}, {'column'});
p.addRequired('x',isValidX);
p.parse(x);

% Initialize the result
result = x;

% Iterate
for k=1:5
    result = funcHandle(result);
end

end

Now what I want to be able to do is validate funcHandle by asking the question:

"Does funcHandle refer to a function that takes a vector as input and returns a vector of the same size as output?"

I suspect there is no built-in way to do this in Matlab, because general Matlab functions have variable output sizes that may depend on the input size.

I was thinking that it is maybe possible to create a custom class vectorFunction that would encapsulate these properties I require? And then I could just validate the function handle by calling

validateattributes(funcHandle, {'vectorFunction'}, {});

However, I have no idea how to make it work meaningfully in practice (if it's possible). I'm new to object-oriented programming.

I found a similar discussion here:

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

but it does not completely satisfy me. I want to be able to validate the handle without calling the function for a specific input.

I have a hunch what I'm asking might really be impossible... But I'd like a clear yes or no.

Thanks in advance for your time.

Ben

Ben
  • 213
  • 1
  • 7
  • If you need to know that for a specific input size `N`, use something like `assert(isequal(size(funcHandle(ones(1,N))), [1 N]))`. If you have to check for all possible sizes or even for "all" actual values passed to the function it becomes complicated. In any case, I don't see how you would do that without doing some actual calls to the function – Luis Mendo Oct 26 '17 at 10:09
  • Can you not implement an error handler in case the call to the function fails (because of incorrect number of input/output arguments)? Validating functions might create a lot of computational overhead, especially if the the function validating its arguments is called often (in a loop). – zeeMonkeez Oct 26 '17 at 10:44

0 Answers0