Validate Name-Value Arguments - MATLAB & Simulink - MathWorks United Kingdom (2024)

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 the Repeating attribute

  • Must 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.Name2end

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 endend

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 and height are required positional arguments of type double.

  • lineOptions.LineStyle is a scalar string with a default value of "-".

  • lineOptions.LineWidth is a scalar numeric with a default value of 1.

  • 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)
However, the same call using 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"])} endend
A user enters this function call intending to set the values of tag to "Mag" and unit to "coulomb":
mySignal("Mag","coulomb")
However, MATLAB, through partial matching, parses "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"])} endend
Because MATLAB does not parse required inputs as name-value arguments, the same function call now sets the value of 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.?ClassNamestructName.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")

See Also

namedargs2cell | arguments

Related Topics

  • Argument Definitions
  • Validate Required and Optional Positional Arguments
  • Validate Repeating Arguments
  • Argument Validation Functions
  • Validate Property Values

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Validate Name-Value Arguments- MATLAB & Simulink- MathWorks United Kingdom (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Validate Name-Value Arguments
- MATLAB & Simulink
- MathWorks United Kingdom (2024)

FAQs

What to do when MATLAB says not enough input arguments? ›

your function needs to be called with at least three input arguments. Therefore you must call it with exactly three input arguments. From the text of the error message you're likely calling it with fewer than three input arguments.

What are name-value arguments in MATLAB? ›

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.

What is the function argument validation in MATLAB? ›

Function argument validation is a way to declare specific restrictions on function arguments. Using argument validation you can constrain the class, size, and other aspects of arguments without writing code in the body of the function to perform these tests.

How do you validate input types in MATLAB? ›

You can specify the class, size, and other aspects of input variables in your entry-point MATLAB function by using arguments blocks to perform function argument validation. Specifying input types using arguments blocks supports: Numeric, logical, half, character, string, and enumeration data types.

How do I fix errors in MATLAB? ›

If you are unfamiliar with the problem, right-click the highlighted code. The first item in the context menu shows the suggested fix. Select the item to apply the fix. If multiple instances of a problem exist, MATLAB might offer to apply the suggested fix for all instances of the problem.

What do too many input arguments mean in MATLAB? ›

Too many input arguments

This error message means that you are providing more input variables into a function than it is designed to handle.

What is an example of an argument in MATLAB? ›

For example, if you create a function named myplot with repeating arguments X , Y , and style , the function accepts multiple sets of these three arguments, such as myplot(x1,y1,style1,x2,y2,style2) . MATLAB creates a cell array that contains all the values passed in for that argument.

How to do data validation in MATLAB? ›

Select Validation Data
  1. On the Curve Fitter tab, in the Data section, click Validation Data. The app opens the Select Validation Data dialog box.
  2. In the dialog box, select variables for X data and Y data (and Z data for surfaces). ...
  3. Close the dialog box.

What is argument based validation? ›

An argument-based approach to validation redresses the balance by linking the kinds of evidence needed to validate a test-score interpretation to the details of the interpretation.

How do you validate input data? ›

Input validation can be implemented using any programming technique that allows effective enforcement of syntactic and semantic correctness, for example: Data type validators available natively in web application frameworks (such as Django Validators, Apache Commons Validators etc).

How to check type of value in MATLAB? ›

Direct link to this answer
  1. To get the data type, or class, of a variable, use the “class” function.
  2. To determine if a variable has a specified data type, use the “isa” function.
  3. For a list of functions that determine if variables have specific attributes, see “is*”.
Nov 15, 2013

What are different input validation? ›

Different types of input validation can be used, including data type validation, range validation, format validation, and consistency validation. By following best practices for implementing input validation, we can build more accurate and secure machine learning models.

What is input argument in MATLAB? ›

arguments ... end declares input arguments for a function. The arguments block is optional. If you include one or more arguments blocks, they must appear before the first executable line of the function. MATLAB® treats any argument block that is not labeled explicitly with Input or Output as an input block.

How do you get MATLAB to ask for input? ›

x = input( prompt ) displays the text in prompt and waits for the user to input a value and press the Return key. The user can enter expressions, like pi/4 or rand(3) , and can use variables in the workspace. If the user presses the Return key without entering anything, then input returns an empty matrix.

How do you add input arguments in MATLAB App Designer? ›

To add input arguments to an app, open the app in App Designer and click Code View. Then click App Input Arguments in the Editor tab. This launches the App Details dialog box. Use the Input Arguments field in the dialog box to add or remove input arguments in the function signature of the startupFcn callback.

How do you make input arguments optional in MATLAB? ›

MATLAB lets you ignore arguments by passing a tilde character ( ~ ) in place of the argument. You can define a function that ignores unused positional arguments by adding a tilde character ( ~ ) in the arguments block corresponding to the position of the argument in the function signature.

Top Articles
Alizay - Tourismus, Urlaub & Wochenende
tourism, attractions and travel guide for Alizay
3 Tick Granite Osrs
Ups Customer Center Locations
Libiyi Sawsharpener
Plaza Nails Clifton
Amtrust Bank Cd Rates
How to Type German letters ä, ö, ü and the ß on your Keyboard
Here's how eating according to your blood type could help you keep healthy
Stolen Touches Neva Altaj Read Online Free
Apnetv.con
A Fashion Lover's Guide To Copenhagen
[PDF] INFORMATION BROCHURE - Free Download PDF
Ladyva Is She Married
C Spire Express Pay
Cooktopcove Com
Craigslist Alabama Montgomery
سریال رویای شیرین جوانی قسمت 338
Louisiana Sportsman Classifieds Guns
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Juicy Deal D-Art
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Rochester Ny Missed Connections
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
4Oxfun
Skepticalpickle Leak
Imagetrend Elite Delaware
Nurofen 400mg Tabletten (24 stuks) | De Online Drogist
Prévisions météo Paris à 15 jours - 1er site météo pour l'île-de-France
Angel del Villar Net Worth | Wife
APUSH Unit 6 Practice DBQ Prompt Answers & Feedback | AP US History Class Notes | Fiveable
Promatch Parts
Kaiser Infozone
Emiri's Adventures
Puerto Rico Pictures and Facts
Despacito Justin Bieber Lyrics
Labyrinth enchantment | PoE Wiki
2020 Can-Am DS 90 X Vs 2020 Honda TRX90X: By the Numbers
Nba Props Covers
Appraisalport Com Dashboard Orders
13 Fun & Best Things to Do in Hurricane, Utah
Haunted Mansion (2023) | Rotten Tomatoes
Gary Vandenheuvel Net Worth
Sandra Sancc
Missed Connections Dayton Ohio
Fallout 76 Fox Locations
Deviantart Rwby
Lsreg Att
Ubg98.Github.io Unblocked
Bomgas Cams
Inloggen bij AH Sam - E-Overheid
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6302

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.