问题
A lot of MATLAB functions have an input structure such as:
output = function MyFun(a,b,c,'-setting1',s1,'-setting2',s2,'-setting3',s3)
I am wondering how I should implement this kind of functionality in my own functions. To be precise, I would like to find out how I can create a function such that:
The function has a variable number of inputs
N + M
The first
N
inputs are ordered and unlabeled. In the example above,N = 3
. The first input is alwaysa
, second input is alwaysb
, third input is alwaysc
. The function input is variable in that users do not necessarily need to sendb
,c
; when they do not then these can take on default (hardcoded) values. As far as I know, this type of functionality is generally handled viavarargin.
The remaining
M
inputs are unordered, but labeled. In the example above,M = 3
, the variables are s1,s2,s3 and their labels aresetting1
,setting2
andsetting3
respectively, I would like for users to be able to specify these variables in whatever order they want. If users choose not to specify one of these inputs (i.e.setting1
), then I would like my function to assign default values fors1.
One example of such a function is the dlmwrite function.
Ideally, I am looking for an approach that is typically used by MATLAB developers so that my code is easy to understand.
回答1:
The InputParser class addresses all of these issues. You can specify any number of:
- Required parameters (ordered, unlabeled)
- Optional parameters (ordered, unlabeled)
- String parameter-value pairs in any order (unordered, labeled)
A very clear tutorial with examples is provided by MathWorks. For a function defined as function printPhoto(filename,varargin)
, the example boils down to the following.
Create the inputParser
:
p = inputParser;
Specify defaults and define validation criteria:
defaultFinish = 'glossy';
validFinishes = {'glossy','matte'};
checkFinish = @(x) any(validatestring(x,validFinishes));
defaultColor = 'RGB';
validColors = {'RGB','CMYK'};
checkColor = @(x) any(validatestring(x,validColors));
defaultWidth = 6;
defaultHeight = 4;
Define required/optional/parameter input names, set their default values and validation functions:
addRequired(p,'filename',@ischar);
addOptional(p,'finish',defaultFinish,checkFinish);
addOptional(p,'color',defaultColor,checkColor);
addParameter(p,'width',defaultWidth,@isnumeric);
addParameter(p,'height',defaultHeight,@isnumeric);
Parse the inputs into a struct:
parse(p,filename,varargin{:});
Then you have the input arguments and their values in p.Results
.
The InputParser
class is used throughout newer MathWorks functions, so don't be afraid to use it yourself!
来源:https://stackoverflow.com/questions/20337721/functions-with-a-flexible-list-of-ordered-unordered-and-labeled-unlabeled-inputs