A main function receives a variable number of arguments. It then needs to call other functions that can depend on these optional inputs.
I want to assign a meaningful default value and check the validity of the optional parameter (parameter B in the following example) only in the function that actually uses it (fctB). Unfortunately, I have to assign a value to B in the main function, when I extract it from varargin. At that point the input parser pB considers that parameter B is being passed to fctB and will not use the default value (even though this is what I want).
Here is a code that illustrates the problem:
function dispatch(varargin) p = inputParser; paramName = 'A'; defaultVal = {}; addOptional(p,paramName,defaultVal); paramName = 'B'; defaultVal = {}; addOptional(p,paramName,defaultVal); paramName = 'C'; defaultVal = {}; addParameter(p,paramName,defaultVal); p.parse(varargin{:}); B = p.Results.B; fctB(B);endfunction fctB(varargin) pB = inputParser; paramName = 'B'; defaultVal = 10; validationFcn = @(x) validateattributes(x,{'numeric'},{'scalar','positive','integer'}); addOptional(pB,paramName,defaultVal,validationFcn); pB.parse(varargin{:}); B = pB.Results.B; disp(['B = ',num2str(B)]);end
Calling the function using, for instance, the value B = 2 produces the correct result
dispatch(1,2)
But calling it without arguments will throw an error due to the validation function for B.
Is there a way to pass an argument to a function in such a way that the input parser for that function recognizes that the argument has not been initialized and uses the default value instead? I guess I am looking for something equivalent to the content of an empty cell array {:}.
If this does not exist in MATLAB, how is such a problem resolved in other languages such as C++?
Best Answer