我发现parseArgs函数非常有用。
这是它的文档:
用于解析的辅助函数varargin
。使编写接受如下参数的函数变得容易:subaxis(4,2,1,'spacing',0,'marginleft',.1,'H','pt',.1)
ArgStruct=parseArgs(varargin,ArgStruct[,FlagtypeParams[,Aliases]])
ArgStruct
是一个充满了具有默认值的命名参数的结构。
- Flagtype 参数是不需要值的参数。(如果存在,该值将设置为 1)
- 别名可用于将一个参数名称映射到多个 argstruct 字段
示例用法:
function parseargtest(varargin)
%define the acceptable named arguments and assign default values
Args=struct('Holdaxis',0, ...
'SpacingVertical',0.05,'SpacingHorizontal',0.05, ...
'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ...
'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ...
'rows',[],'cols',[]);
%The capital letters define abrreviations.
% Eg. parseargtest('spacingvertical',0) is equivalent to parseargtest('sv',0)
Args=parseArgs(varargin,Args, ...
% fill the arg-struct with values entered by the user, e.g.
% {'Holdaxis'}, ... %this argument has no value (flag-type)
% {'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}});
disp(Args)