I'm setting up some default options with a struct:
defaults.color = 'r';
defaults.marker = 'o';
defaults.text = false;
A user can now change some of the default option. e.g.:
options.color = 'k';
Now I'd like to overwrite the default options with the options changed by the user:
finaloptions = Overwrite(defaults, options)
Giving:
finaloptions.color = 'k';
finaloptions.marker = 'o';
finaloptions.text = false;
Is there a function that does this for me or do I have to program it myself?
Thanks,
Ralph
why not initialize options.color to defaults.color
then set
finaloptions.color=options.color
?
Because the only thing the user should need to do is to setup those option they want to change.
Yes, I could give them the defaults-structure but I don't want to. And yes, it's only cosmetics, I know.
Ralph
You might find some good ideas in these 2 posts:
http://blogs.mathworks.com/loren/2009/05/05/nice-way-to-set-function-
defaults/
http://blogs.mathworks.com/loren/2009/05/12/optional-arguments-using-
empty-as-placeholder/
--
Loren
http://blogs.mathworks.com/loren
http://matlabwiki.mathworks.com/MATLAB_FAQ
Incidentally, the above file requires that you pass the options as string-value pairs. Below is a wrapper that I routinely use, which will allow you to pass options in structure form as well.
function [varargout]=optionproc(default, options, varargin)
%Process options encapsulated as either a structure or as a cell array
%
%[optionstruct,extras]=optionproc(default, options, varargin)
%
% default: structure of default values
% options: a structure whose fields are given values or a cell array
% of the form {'Option1',Option1,'Option2',Option2,...}
%
% varargin: arguments to be passed to vararg_pair.m
nn=length(options);
if nn==0
optionstruct=default;
varargout{1}=default;
varargout{2}={};
return
elseif iseven(nn)
varargs=options;
elseif nn==1 %structure input mode
if iscell(options),
options=options{1};
end
if ~isstruct(options), error 'Attempted structure mode input?'; end
varargs=[fieldnames(options),struct2cell(options)]';
varargs=varargs(:)';
else
error 'Unrecognized Input'
end
varargout=cell(1,nargout);
[varargout{:}]=vararg_pair(default,varargs,varargin{:});
HTH.
Bjoern
> Yup, there is catstruct.m to be found on the file exchange:
> http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct
==============
Careful.
Since catstruct() will always consolidate the fields, it means that
it will be susceptible to typos and spelling mistakes.
For example, if default.color='k', but someone inputs an option accidentally using a British spelling like options.colour='g', then default.color will not be overwritten.
These kinds of errors can be hard to detect...