Generate Field Names from Variables
This example shows how to derive a structure field name at run time from a variable or expression.
The general syntax is
structName.(dynamicExpression)
where dynamicExpression is a variable or expression that, when evaluated, returns a character
vector or, starting in R2017b, a string scalar. Field names that you reference with expressions are
called dynamic fieldnames, or sometimes dynamic field names.
For example, create a field name from the current date:
currentDate = datestr(now,'mmmdd');
myStruct.(currentDate) = [1,2,3]
If the current date reported by your system is February 29, then this code assigns data to a field
named Feb29:
myStruct =
Feb29: [1 2 3]
The dynamic fieldname can return either a character vector or a string scalar. For example, you can
specify the field Feb29 using either single or, starting in R2017b, double quotes.
myStruct.('Feb29')
ans =
1
2
3
myStruct.("Feb29")
ans =
1
2
3
Field names, like variable names, must begin with a letter, can contain letters, digits, or underscore
characters, and are case sensitive. To avoid potential conflicts, do not use the names of existing
variables or functions as field names.
See Also
struct | fieldnames | getfield | setfield
Related Examples
•
“Variable Names” on page 1-5
•
“Structure Arrays” on page 11-2
11 Structures
11-10
This example shows how to derive a structure field name at run time from a variable or expression.
The general syntax is
structName.(dynamicExpression)
where dynamicExpression is a variable or expression that, when evaluated, returns a character
vector or, starting in R2017b, a string scalar. Field names that you reference with expressions are
called dynamic fieldnames, or sometimes dynamic field names.
For example, create a field name from the current date:
currentDate = datestr(now,'mmmdd');
myStruct.(currentDate) = [1,2,3]
If the current date reported by your system is February 29, then this code assigns data to a field
named Feb29:
myStruct =
Feb29: [1 2 3]
The dynamic fieldname can return either a character vector or a string scalar. For example, you can
specify the field Feb29 using either single or, starting in R2017b, double quotes.
myStruct.('Feb29')
ans =
1
2
3
myStruct.("Feb29")
ans =
1
2
3
Field names, like variable names, must begin with a letter, can contain letters, digits, or underscore
characters, and are case sensitive. To avoid potential conflicts, do not use the names of existing
variables or functions as field names.
See Also
struct | fieldnames | getfield | setfield
Related Examples
•
“Variable Names” on page 1-5
•
“Structure Arrays” on page 11-2
11 Structures
11-10
