Starting in MATLAB R2021a, name-value arguments have a new optional syntax!
A property name can be paired with its value by an equal sign and the property name is not enclosed in quotes.
Compare the comma-separated name,value syntax to the new equal-sign syntax, either of which can be used in >=r2021a:
- plot(x, y, "b-", "LineWidth", 2)
- plot(x, y, "b-", LineWidth=2)
It comes with some limitations:
- It's recommended to use only one syntax in a function call but if you're feeling rebellious and want to mix the syntaxes, all of the name=value arguments must appear after the comma-separated name,value arguments.
- Like the comma-separated name,value arguments, the name=value arguments must appear after positional arguments.
- Name=value pairs must be used directly in function calls and cannot be wrapped in cell arrays or additional parentheses.
Some other notes:
- The property names are not case-sensitive so color='r' and Color='r' are both supported.
- Partial name matches are also supported. plot(1:5, LineW=4)
The new syntax is helpful in distinguishing property names from property values in long lists of name-value arguments within the same line.
For example, compare the following 2 lines:
h = uicontrol(hfig, "Style", "checkbox", "String", "Long", "Units", "Normalize", "Tag", "chkBox1")
h = uicontrol(hfig, Style="checkbox", String="Long", Units="Normalize", Tag="chkBox1")
Here's another side-by-side comparison of the two syntaxes. See the attached mlx file for the full code and all content of this Community Highlight.
19 Comments
I am enjoying so far the new feature "Name=Value", however, a real drawback is the lack of Code Suggestions and Completions when employing this syntax. Are there any plans on extending the Code Suggestions and Completions capabilities already present on .mlx files when using the classic "Name","Value" pairs syntax?
It is better to get the hints when we use Name=Value syntax when typing m-scripts. Another thing is how to make the user-defined function available to this syntax.
A = [ 1 2 3 4 ] B = padarray(A,3,9,'pre') % official document example, It is not easy to see the meaning of the numbers 3 and 9 B = padarray(A,padsize=3,padval=9,direction='pre') % Desired enhancements,but there is an error!
The benefits I see are maily for people who didn't use line breaks (with ...) to separate arguments.
One thing I couldn't find in the documentation: the parameter name will be provided to the function as a string in the varargin cell array. So if your input parsing already allowed scalar strings in addition to char arrays, you don't even have to change your functions.
If you plan on using my minify function, make sure you don't use this (this is a legal syntax in R2021a):
FontSize=12; text(0.5,0.5,'a',FontSize=FontSize)