📄 parseopts.m
字号:
function opts = parseopts(opts, varargin)
% parseopts - parse optional input arguments with defaults
%
% FORMAT: opts = parseopts(opts, ...)
%
% Input fields:
%
% opts 1x1 struct with defaults for options
% ... string/value pairs, 1x1 structs or opt=value strings
%
% Output fields:
%
% opts 1x1 struct with filled options
%
% Note: input arguments are processed in given order;
% argument names in ... are case *insensitive*
% Version: v0.5c
% Build: 6120415
% Date: Dec-04 2006, 3:15 PM CET
% Author: Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools
% argument check
if nargin < 1 || ...
~isstruct(opts) || ...
numel(opts) ~= 1 || ...
length(fieldnames(opts)) < 1
error( ...
'BVQXtools:BadArgument', ...
'Invalid or missing opts struct.' ...
);
end
% get list of valid options and args
hasopts = fieldnames(opts);
valopts = lower(hasopts);
valvars = varargin;
% parse all other args
ac = 1;
while ac <= length(valvars)
% get next argument
nextarg = valvars{ac};
ac = ac + 1;
% reject empty arguments
if isempty(nextarg)
continue;
end
% type of argument
switch (lower(class(nextarg)))
% char arguments
case {'char'}
% linearize
nextarg = nextarg(:)';
% is a name=val option
nameval = find(nextarg == '=');
if ~isempty(nameval)
valvars = [valvars(1:ac-1), ...
{nextarg(1:nameval(1)-1), nextarg(nameval(1)+1:end)}, ...
valvars(ac:end)];
% option, value pair
else
% ac invalid already
if ac > length(valvars)
error( ...
'BVQXtools:TooFewArguments', ...
'Missing value for option ''%s''.', ...
nextarg ...
);
end
% get option value and increase ac
nextval = valvars{ac};
ac = ac + 1;
% find correct option
parnum = find(strcmpi(nextarg, valopts));
if isempty(parnum)
warning( ...
'BVQXtools:UnknownOption', ...
'Unknown option name: ''%s''.', ...
nextarg ...
);
continue;
end
% set option
opts.(hasopts{parnum(1)}) = nextval;
end
% struct arguments
case {'struct'}
% only valid for 1x1 structs
if numel(nextarg) ~= 1
continue;
end
% put contents into valvars
argf = fieldnames(nextarg);
argc = {};
for fc = 1:length(argf)
argc = [argc, {argf{fc}, nextarg.(argf{fc})}];
end
valvars = [valvars(1:ac-1), argc(:)', valvars(ac:end)];
% unsupported type
otherwise
warning( ...
'BVQXtools:BadArgument', ...
'Unsupported input argument type.' ...
);
continue;
end
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -