Last active
July 14, 2017 19:36
-
-
Save sg-s/ffd81d88a018a3852ba4 to your computer and use it in GitHub Desktop.
MATLAB name value pair parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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