Parsing arguments

From NA-Wiki

Jump to: navigation, search
function opt = getopts(args,varargin)
%GETOPTS  Parse arguments and return a struct
%   OPT = GETOPTS(ARGS,NAME1,VALUE1,NAME2,VALUE2,...)
%   ARGS is a cell array holding all valid arguments.
%
%   Remark: GETOPTS is case sensitive.  
%
%   Hint: OPT = GETOPTS(ARGS,VARARGIN{:});

%   Henrik Holst
%   Fri, 16 May 2008 21:37:50 +0200

opt = struct;
if isempty(varargin)
	return
end
names = {varargin{1:2:end-1}};
values = {varargin{2:2:end}};
data = cell2struct(values,names,2);
for k = 1:length(names)
	name = names{k};
	if ismember(name,args)
		opt = setfield(opt,name,getfield(data,name));
	else
		warning(['Unrecognized property name ''' name '''']);
	end
end
Personal tools