Skip to content

Instantly share code, notes, and snippets.

@timlod
Last active July 24, 2017 11:59
Show Gist options
  • Save timlod/c98c5b65f4590ae87008d8124917dfa9 to your computer and use it in GitHub Desktop.
Save timlod/c98c5b65f4590ae87008d8124917dfa9 to your computer and use it in GitHub Desktop.
MATLAB option parser skeleton
% I use parts of the code of export_fig for this skeleton, scrapped of its specific details.
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-, Tim Loderhose 2016
% https://github.com/altmany/export_fig | https://github.com/altmany/export_fig/blob/master/LICENSE
function options = parseArgs(varargin)
% Parse the input arguments
% Set the defaults
options = struct(...
'opt1', 'arg1default', ...
'opt2', true, ...
'opt3', false, ...
'opt4', 'arg4default', ...
'opt5', [1 2 3]);
% Go through the other arguments
skipNext = false;
for i = 1:nargin
% Skip if key value pair was parsed (value would be this iteration but was
% already read)
if skipNext
skipNext = false;
continue;
end
% Check for
if ischar(varargin{i}) && ~isempty(varargin{i})
if varargin{i}(1) == '-'
switch lower(varargin{i}(2:end))
case 'opt1arg'
options.opt1 = false;
case 'opt1arg'
options.opt1 = false;
case 'opt1arg'
options.opt1 = false;
case 'opt1arg'
options.opt1 = false;
otherwise
try
wasError = false;
% Case of -X<val> - match value next to -letter to
% parse the argument, skip next option (that was the
% letter in case a space was put in.
val = str2double(regexp(varargin{i}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
if isempty(val) || isnan(val)
% Issue #51: improved processing of input args (accept space between param name & value)
val = str2double(varargin{i+1});
if isscalar(val) && ~isnan(val)
skipNext = true;
end
end
if ~isscalar(val) || isnan(val)
wasError = true;
error('Option %s not recognised or cannot be parsed', varargin{i});
end
catch err
% We might have reached here by raising an intentional error
if wasError % intentional raise
rethrow(err)
else % unintentional
error(['Unrecognized input option: ''' varargin{i} '''']);
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment