function opts=optndfts(args,varargin)
% optndfts Create option struct with default values for those not given
% 2012-10-31 Matlab8 Copyright (c) 2012, W J Whiten BSD License
%
% opts=optndfts(args,varargin)
% args Either a struct, giving a cell array of name
% or first element of cell array containing cell
% of name value pairs. Matches containing routine using
% varargin for a list of name values pairs, (or struct or cell
% array of name for value pairs).
% varargin Either a list of name value pairs, or a struct, or a cell
% array of name value pairs.
%
% opts Struct giving option values
%
% Use to process optional arguments given as name value pairs, a cell
% array of name value pairs, or as a struct. Default values from
% optndfts call are used for values not given in args.
%
% Example:
% Using optndft within a function as follows:
% function strt=demo(a,vargargin)
% strt=optndft(varargin,'aa',1,'bb',2,'cc',3);
% end
% Then demo could be called as:
% demo(1,'bb',22)
% And optndft fills in default values for those not given::
% ans =
% aa: 1
% bb: 22
% cc: 3
%
% See also: inputParser
% if input args not a struct convert to struct
if(iscell(args))
if(~isempty(args) && iscell(args{1}))
args=args{1};
if(iscell(args))
args=struct(args{:});
end
else
args=struct(args{:});
end
end
% convert varargin inputs to a struct
if(~isempty(varargin) && iscell(varargin{1}))
dft=varargin{1};
if(iscell(dft))
dft=struct(dft{:});
end
else
dft=struct(varargin{:});
end
% start with default values
opts=dft;
% copy new values over default values
names=fieldnames(args);
for i=1:length(names)
if(~isfield(opts,names{i}))
error(['Invalid field name ',names{i}])
end
opts.(names{i})=args.(names{i});
end
return
end