MATLAB: Bug in the parse, inputParser family of functions

buginputparserparse

I've stumbled upon what sure appears to me to be a bug in the parse and parseInput suite of functions. It seems to have to do with some combination of having character strings as arguments, having a valid function apply to check the validity of the arguments, and the order in which the arguements are provided. Here's perhaps the simpliest code to reproduce the issue:
tryOne = myParse('alpha','one', 'beta','two')
tryTwo = myParse('beta', 'two', 'alpha','one')
function results = myParse(varargin)
parseObj = inputParser;
addOptional(parseObj, 'alpha', 'none', @(x) ( isstring(x) || ischar(x) ) );
addOptional(parseObj, 'beta', 'none', @(x) ( isstring(x) || ischar(x) ) );
parse(parseObj,varargin{:})
results = parseObj.Results;
end
Note that the only difference between the first and second call to "myParse" is the order of the arguements. Running this little test code returns the wrong result in the first case:
tryOne =
struct with fields:
alpha: 'alpha'
beta: 'two'
Notice that 'alpha' is set to the string 'alpha' instead of being set to 'one', but 'beta' is set correctly. However, in the second call (tryTwo), with the order of the args just reversed, the correct result is returned.
TryTwo =
struct with fields:
alpha: 'one'
beta: 'two'
BTW, if I run the first try again, it gets the answer wrong again, so its not a matter of just the first call to parse returning the wrong answer.
I've tried all kinds of variants of the above, including numeric args, including or not including a validation check function in "addOptional", some of which seem to work correctly and some don't. But the example here seems to illustrate the issue most simply.
The parse/parseInput suite of functions are built-ins, so I can't dive into the code of those functions to figure out what is really going on here.

Best Answer

Note that the only difference between the first and second call to "myParse" is the order of the arguements.
If the order is not supposed to matter, you should be using addParameter rather than addOptional,
tryOne = myParse('alpha','one', 'beta','two')
tryOne = struct with fields:
alpha: 'one' beta: 'two'
tryTwo = myParse('beta', 'two', 'alpha','one')
tryTwo = struct with fields:
alpha: 'one' beta: 'two'
function results = myParse(varargin)
parseObj = inputParser;
addParameter(parseObj, 'alpha', 'none', @(x) ( isstring(x) || ischar(x) ) );
addParameter(parseObj, 'beta', 'none', @(x) ( isstring(x) || ischar(x) ) );
parse(parseObj,varargin{:})
results = parseObj.Results;
end