0
0
MATLABdata~5 mins

Dynamic field names in MATLAB

Choose your learning style9 modes available
Introduction
Dynamic field names let you create or access parts of a structure using names stored in variables. This helps when you don't know the field names before running the program.
When you want to store data with names that come from user input.
When you need to loop over a list of names to create or read fields in a structure.
When you want to build a structure with fields based on changing conditions.
When you want to write flexible code that works with different sets of field names.
Syntax
MATLAB
value = structName.(fieldNameVariable);  % Access field
structName.(fieldNameVariable) = value;  % Assign field
The field name is inside parentheses and single quotes are not used around the variable.
The variable fieldNameVariable must be a string or character vector.
Examples
Creates a field 'age' in the structure person and sets it to 30.
MATLAB
fieldName = 'age';
person.(fieldName) = 30;
Reads the value of the field 'score' from the structure data.
MATLAB
field = 'score';
value = data.(field);
Creates fields 'height' and 'weight' in stats with values 10 and 20.
MATLAB
fields = {'height', 'weight'};
for i = 1:length(fields)
    stats.(fields{i}) = i * 10;
end
Sample Program
This program creates a structure person and adds fields 'name' and 'age' using dynamic field names. Then it shows the structure.
MATLAB
person = struct();
fieldName = 'name';
person.(fieldName) = 'Alice';
fieldName = 'age';
person.(fieldName) = 28;

% Display the structure
disp(person);
OutputSuccess
Important Notes
Dynamic field names are useful but can make code harder to read if overused.
Make sure the field name variable contains valid field names (no spaces or special characters).
Use dynamic field names to write flexible and reusable code.
Summary
Dynamic field names let you use variables to name structure fields.
They help when field names are not fixed before running the program.
Use the syntax structName.(fieldNameVariable) to get or set fields.