Validate Name-Value Arguments
Name-value arguments associate a name with a value that is passed to the function. Name-value arguments:
Can be passed to the function in any order
Are always optional
Must be declared after all positional and repeating arguments
Cannot appear in an
arguments
block that uses theRepeating
attributeMust use unique names even when using multiple name-value structures
Cannot use names that are also used for positional arguments
Declare name-value arguments in an arguments
block using dot notation
to define the fields of a structure. For example, the structure named
NameValueArgs
defines two name-value arguments, Name1
and Name2
. You can use any valid MATLAB® identifier as the structure name.
arguments NameValueArgs.Name1 NameValueArgs.Name2 end
The structure name must appear in the function signature.
function myFunction(NameValueArgs)
Call the function using the field names in the name-value structure.
myFunction(Name1=value1,Name2=value2)
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. Both syntaxes are valid in later releases.
The name of the structure used in the function signature is the name of the structure in the function workspace that contains the names and values passed to the function.
function result = myFunction(NameValueArgs) arguments NameValueArgs.Name1 NameValueArgs.Name2 end % Function code result = NameValueArgs.Name1 * NameValueArgs.Name2; end
r = myFunction(Name1=3,Name2=7)
r = 21
Name-value arguments support partial name matching when there is no ambiguity. For
example, a function that defines LineWidth
and LineStyle
as its two name-value arguments accepts LineW
and LineS
,
but using Line
results in an error. In general, using full names is the
recommended practice to improve code readability and avoid unexpected behavior.
The same name-value argument can be repeated in a function call without error, but the
last version specified is the one MATLAB honors. For example, this call to plot
specifies the value
for Color
twice. MATLAB displays the plot in red.
plot(x,y,Color="blue",LineStyle="--",Color="red")
Default Values for Name-Value Arguments
You can specify a default value for each name. If you do not specify a default value and the function is called without that name-value argument, then that field is not present in the name-value structure. If no name-value arguments are passed to the function, MATLAB creates the structure, but it has no fields.
To determine what name-value arguments have been passed in the function call, use the
isfield
function.
For example, the following function defines two required positional arguments
(width
and height
) and two name-value arguments
(LineStyle
and LineWidth
). In this example, the
options
structure has two fields (LineStyle
and
LineWidth
) containing either the default values or values specified as
name-value arguments when the function is called.
function myRectangle(width,height,options) arguments width double height double options.LineStyle (1,1) string = "-" options.LineWidth (1,1) {mustBeNumeric} = 1 end % Function code ... end
All of these syntaxes are valid ways to call this function.
myRectangle(4,5) myRectangle(4,5,LineStyle=":",LineWidth=2) myRectangle(4,5,LineWidth=2,LineStyle=":") myRectangle(4,5,LineStyle=":") myRectangle(4,5,LineWidth=2)
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myRectangle(4,5,"LineStyle",":","LineWidth",2) myRectangle(4,5,"LineWidth",2,"LineStyle",":")
Using Repeating and Name-Value Arguments
If the function defines repeating arguments, then you must declare the name-value
arguments in a separate arguments
block that follows the repeating
arguments block. For example, this function accepts two repeating arguments,
x
and y
. After specifying all repeats of
x
and y
, you can specify a name-value argument that
assigns the value lin
or log
to the
PlotType
name.
To determine if the function call includes the PlotType
argument, use
the isfield
function to check for the PlotType
field
in the scale
structure.
function myLinLog(x,y,scale) arguments(Repeating) x (1,:) double y (1,:) double end arguments scale.PlotType (1,1) string end z = reshape([x;y],1,[]); if isfield(scale,"PlotType") if scale.PlotType == "lin" plot(z{:}) elseif scale.PlotType =="log" loglog(z{:}) end end end
Call this function with or without the name-value argument.
myLinLog(1:5,1:5)
myLinLog(1:5,1:5,1:10,1:100:1000)
myLinLog(1:5,1:5,1:10,1:100:1000,PlotType="log")
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myLinLog(1:5,1:5,1:10,1:100:1000,"PlotType","log")
Multiple Name-Value Structures
Function argument blocks can contain multiple name-value structures. However, the field
names must be unique among all structures. This function has two name-value structures:
lineOptions
and fillOptions
. These structures cannot
have the same field names.
The arguments in the myRectangle
function are:
width
andheight
are required positional arguments of typedouble
.lineOptions.LineStyle
is a scalar string with a default value of"-"
.lineOptions.LineWidth
is a scalar numeric with a default value of1
.fillOptions.Color
is a string.fillOptions.Pattern
has no restrictions on its value.
function myRectangle(width,height,lineOptions,fillOptions) arguments width double height double lineOptions.LineStyle (1,1) string = "-" lineOptions.LineWidth (1,1) {mustBeNumeric} = 1 fillOptions.Color string fillOptions.Pattern end % Function Code ... end
Robust Handling of Name-Value Arguments
The best practice for implementing name-value arguments in your functions is by defining
them in an arguments block. An arguments block eliminates the need to write your own code to
parse the name-value arguments, and the block also helps implement robust argument parsing
for both the "name",value
syntax and the name=value
syntax introduced in R2021a.
Enforcing Valid Names
Defining a name-value argument in an arguments block ensures that the name is a valid
identifier. In turn, this helps ensure that your arguments work with both
"name",value
and name=value
syntaxes. For example,
a name-value argument that uses an invalid identifier can work with the comma-separated
syntax:
myFunction(data,"allow-empty",true)
allow-empty=true
throws an error. Defining the
name-value argument in an arguments block ensures that the names you define are valid
MATLAB variable names and compatible with the name=value
syntax.Avoiding Unexpected Results with Text Inputs
Functions that include both optional text inputs and name-value arguments run the risk of MATLAB interpreting text inputs as the names of the name-value arguments. This function includes two optional text inputs and a name-value argument.
function mySignal(tag,unit,opts) arguments tag = "0" unit = "ampere" opts.Magnifier {mustBeMember(opts.Magnifier,["small","medium","big"])} end end
tag
to
"Mag"
and unit
to
"coulomb"
:mySignal("Mag","coulomb")
"Mag"
as the name-value
argument Magnifer
. "coulomb"
is not a valid value
for that name, so the function errors.One way to avoid this is to make tag
a required argument by
removing its default
value:
function mySignal(tag,unit,opts) arguments tag unit = "ampere" opts.Magnifier {mustBeMember(opts.Magnifier,["small","medium","big"])} end end
tag
to "Mag"
and does
not error.Another option is to make all three inputs name-value arguments. This helps users avoid mistakes when specifying inputs because each value is associated with a name, and the order the user specifies the inputs does not affect the end results.
Name-Value Arguments from Class Properties
A useful function syntax in MATLAB uses the public properties of a class for the names of name-value arguments.
To specify name-value arguments for all settable properties defined by a class (that is, all
properties with public SetAccess
), use this syntax in an
arguments
block:
structName.?ClassName
A function can use the "structName
.?
ClassName
" syntax only once. Therefore, a function can define
only one name-value structure that gets its field names from a class, even if using
different classes and structure names.
If the class places restrictions on values that you can assign to the property by using property validation, then the function applies the validation to the individual name-value arguments. For information on property validation, see Validate Property Values.
For example, this function has two required arguments, x
and
y
and accepts any public property name and value for the
matlab.graphics.chart.primitive.Bar
class.
function myBar(x,y,propArgs) arguments x (:,:) double y (:,:) double propArgs.?matlab.graphics.chart.primitive.Bar end propertyCell = namedargs2cell(propArgs); bar(x,y,propertyCell{:}) end
Call the function with the required inputs and any settable property name-value pairs.
x = [1,2,3;4,5,6]; y = x.^2; myBar(x,y) myBar(x,y,FaceColor="magenta",BarLayout="grouped")
Before R2021a, pass names as strings or character vectors, and separate names and values with commas. For example:
myBar(x,y,"FaceColor","magenta","BarLayout","grouped")
Override Specific Properties
You can override the class property validation by redefining the property name with a specific name-value argument in the arguments block.
structName.?ClassName structName.PropertyName (dim1,dim2,...) ClassName {fcn1,fcn2,...}
The specific name-value argument validation overrides the validation defined by class for the individually specified property name.
For example, the following function defines name-value arguments as the properties of
the matlab.graphics.chart.primitive.Bar
class. The function also
overrides the property name FaceColor
to allow only these specific
values: red
or blue
.
The matlab.graphics.chart.primitive.Bar
class has a default value
for FaceColor
that is not one of the restricted values
(red
or blue
). Therefore, the overriding
declaration must assign a default value that satisfies the restriction placed by the
mustBeMember
validation function. That is,
the default value must be red
or blue
.
This function converts the name-value structure to a cell array containing interleaved
names and values using the namedargs2cell
function.
function myBar(x,y,propArgs) arguments x (:,:) double y (:,:) double propArgs.?matlab.graphics.chart.primitive.Bar propArgs.FaceColor {mustBeMember(propArgs.FaceColor,{'red','blue'})} = "blue" end propertyCell = namedargs2cell(propArgs); bar(x,y,propertyCell{:}) end
Call the function using the two required arguments, x
and
y
. Optionally pass any name-value pairs supported by the bar function
and a value for FaceColor
that can be either red
or
blue
. Other values for FaceColor
are not allowed.
x = [1,2,3;4,5,6]; y = x.^2; myBar(x,y) myBar(x,y,FaceColor="red",BarLayout="grouped")