I am using findArea as an example in documentation to parse and validate required,optional and pair-value arguments of a function. I have copied findArea function here to demonstrate the possible bug in matlab parse function.
function a = findArea(width,varargin) defaultHeight = 1; defaultUnits = 'inches'; defaultShape = 'rectangle'; expectedShapes = {'square','rectangle','parallelogram'}; p = inputParser; validScalarPosNum = @(x) isnumeric(x) && isscalar(x) && (x > 0); addRequired(p,'width',validScalarPosNum); addOptional(p,'height',defaultHeight,validScalarPosNum); addParameter(p,'units',defaultUnits,@isstring); addParameter(p,'shape',defaultShape,... @(x) any(validatestring(x,expectedShapes))); parse(p,width,varargin{:}); a = p.Results.width*p.Results.height; end
Now I am calling the findArea function as given in documentation:
1) a = findArea(7,3,'shape','square');
As expected Validation of 7 (first input) and 3 (second input) is done with validScalarPosNum. For Name-Value pair, validation of value of "shape" is done with validatestring. This is fine.
2) a = findArea(7,'shape','square');
Now the problem is here. Validation of 7 (first input) is done with validScalarPosNum. However, the validation of second input "shape" is also done with validScalarPosNum. This is possibly bug. Then as in 1) Validation of value of "shape" is done with validatestring. The problem arises when the optional input is defined in the function (in this example "height"), but not passed in the function arguments.
Does anybody has an idea what is going on here?
Thank you very much.
Best Answer