Expert Answer:
s:
You're right that the parser appears to give some odd results, a related question might be this one.
One work-around, which works for your function in its current form, would be to add a check for if 2 inputs are given. If there are 2 inputs, assume it's your OnlyDirectories
flag and use the default name
value. The code would look like this and passes all 4 of your example use cases.
function list = dir2(varargin) p = inputParser; addOptional(p, 'name', '.', @ischar); addParameter(p, 'OnlyDirectories', false, @islogical); if numel(varargin) == 2 varargin = [{'.'}, varargin]; end parse(p, varargin{:}); list = dir(p.Results.name); if p.Results.OnlyDirectories dirFlags = [list.isdir]; list = list(dirFlags); end list = list(arrayfun(@(x) ~strcmp(x.name(1),'.'), list)); end
This is a bit hacky though, and has scope to give confusing error messages. It would be better to just have both inputs as name-value pairs
function list = dir2(varargin) p = inputParser; addParameter(p, 'name', '.', @ischar); addParameter(p, 'OnlyDirectories', false, @islogical); % ... other code end