Skip to content

Instantly share code, notes, and snippets.

@sg-s
Last active July 14, 2017 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sg-s/ffd81d88a018a3852ba4 to your computer and use it in GitHub Desktop.
Save sg-s/ffd81d88a018a3852ba4 to your computer and use it in GitHub Desktop.
MATLAB name value pair parsing
% options and defaults
options.foo = 1;
options.bar = 2;
if nargout && ~nargin
varargout{1} = options;
return
end
% validate and accept options
if iseven(length(varargin))
for ii = 1:2:length(varargin)-1
temp = varargin{ii};
if ischar(temp)
if ~any(find(strcmp(temp,fieldnames(options))))
disp(['Unknown option: ' temp])
disp('The allowed options are:')
disp(fieldnames(options))
error('UNKNOWN OPTION')
else
options = setfield(options,temp,varargin{ii+1});
end
end
end
elseif isstruct(varargin{1})
% should be OK...
options = varargin{1};
else
error('Inputs need to be name value pairs')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment