问题
I'm designing a function that takes as argument one structure and any number of flags. The function will contain a couple of if
s checking whether a specific flag is set.
What is the neatest way to achieve this? I was thinking about passing the flags as separate string arguments. Is there a neater solution?
回答1:
I would do it like using varargin
and ismember
:
function foo(arg1,arg2,varargin)
flag1=ismember('flag1',varargin);
flag2=ismember('flag2',varargin);
flag3=ismember('flag3',varargin);
And you can call the function like that:
foo(a1,a2,'flag3','flag1')
This will activate flag1
and flag3
.
回答2:
Pass in a struct
of flags:
options = struct(...
'Flag1', true, ...
'Flag2', true, ...
'MySpecifFlag', false ...
);
Foo(st, options);
To get a list of all the flags that were explicitly set by the user, use fieldnames
:
passedOptions = fieldnames(options);
This returns a cell array whose elements are strings - these strings are the flags set by the user; the i
th element of the array is the i
th flag set by the user.
Access the value of each flag that was set:
options.(passedOptions{i}) %# gets the value of the flag corresponding to passedOptions{i}
回答3:
Probably you can pass varargin - The even will be names of the flags and the odd their values (except the first)
function Foo(st, varargin)
end
Then pass values like this:
Foo(st, 'Flag1', true, 'Flag2', false)
Foo(st, 'Flag3', true, 'MyFlag2', false,'MySpecialFlag',false)
Foo(st)
To access the variable arguments use
varargin{2}, varargin{3},
etc..
To check whether a specific flag was passed, do
flagNames = varargin{2:end};
ismember('MyFlag',flagNames )
回答4:
You can pass the flags as a string with 0s and 1s. The order can be fixed or you can also pass a cell array of flag names.
flagstr = '101'; %# string passed as argument
flaglog = flagstr=='1'; %# logical vector, can be accessed as flaglog(i)
fname = {'flag1','flag2','flag3'}; %# flag names, can be passed as argument or defined in the function
fvalue = num2cell(flaglog); %# create cell array
flags = cell2struct(fvalue, fname, 2); %# create a structure, so you can access a flag with flags.flag1
You need to take care to match the length of fvalue
and fnames
. if they are different you can either generate an error or somehow correct it (remove the extra flags or fill the absent by default value).
回答5:
varargin
is the way to go for parsing a variable number of arbitrary input arguments. If you want somemore control over the calling syntax of the function (i.e. optional/required arguments) then I suggest looking into Matlab's input parser.
来源:https://stackoverflow.com/questions/8596849/what-is-the-neatest-way-of-passing-flags-to-a-matlab-function