Posted on
programming matlab research

I have found the following script useful for dealing with options in Matlab scripts.

processOptions.m
function options = processOptions(optionsInput, optionsDefault)
 
options = optionsDefault;
if (isstruct(optionsInput))
    fields = fieldnames(optionsInput);
    for i=1:length(fields)
        if (~isstruct(getfield(optionsInput, fields{i})))
            options = setfield(options, fields{i}, getfield(optionsInput, fields{i}));
        else
            temp = processOptions(getfield(optionsInput, fields{i}), ...
                            getfield(options, fields{i}) );
            options = setfield(options, fields{i}, temp);
        end
    end
end
 
end % processOptions
The example in myfunction.m demonstrates its usage.
myfunction.m
function myfunction(input, options)
 
options_default = defaultOptions();
if (nargin >= 2)
    options = processOptions(options, options_default);
else
    options = options_default;
end
 
 
% here comes the logic of myfunction which might access some of the options
 
 
end
 
 
function options = defaultOptions()
 
options = [];
options.max_iter = 200;
options.lambda = 1.0;
 
end % defaultOptions




comments powered by Disqus