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.
The
InputParser
class addresses all of these issues. You can specify any number of: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
:Specify defaults and define validation criteria:
Define required/optional/parameter input names, set their default values and validation functions:
Parse the inputs into a struct:
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!