Functions with a flexible list of ordered / unordered and labeled / unmarked inputs in MATLAB

Many MATLAB functions have an input structure, for example:

output = function MyFun(a,b,c,'-setting1',s1,'-setting2',s2,'-setting3',s3) 

I am wondering how can I implement such functionality in my own functions. To be precise, I would like to know how I can create such a function that:

  • The function has a variable number of inputs N + M

  • The first inputs of N ordered and unlabeled . In the above example, N = 3 . The first input is always a , the second input is always b , the third input is always c . The input to the function is variable because users do not have to send b , c ; when they do not, they can take default values ​​(hard-coded). As far as I know, this type of function is usually handled through varargin.

  • The remaining inputs of M disordered, but labeled . In the above M = 3 example, the variables are s1, s2, s3, and their labels are setting1 , setting2 and setting3 respectively, I would like users to be able to specify these variables in any order they want. If users prefer not to specify one of these inputs (i.e. setting1 ), then I would like my function to setting1 default values ​​to s1.

One example of such a function is the dlmwrite function.

Ideally, I'm looking for an approach that is commonly used by MATLAB developers, so my code is easy to understand.

+5
matlab argument-passing variadic-functions
source share
1 answer

The InputParser class addresses all of these issues. You can specify any number:

  • Required parameters (ordered, unlabeled)
  • Additional parameters (ordered, unlabeled)
  • Parameter value of a pair of lines 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 is as follows.

Create an InputParser :

 p = inputParser; 

Specify default values ​​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 the required / optional / names of input parameters, 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 in a struct:

 parse(p,filename,varargin{:}); 

Then you have the input arguments and their values ​​in p.Results .

The InputParser class InputParser used in all of the new MathWorks features, so don't be afraid to use it yourself!

+7
source share

All Articles