Structures in MATLAB
Last Updated :
28 Nov, 2022
In MATLAB, structures are a way to group related data, where different data have different data types. These different data types are stored as fields inside a data container created by the struct command. A struct could have any number of fields ranging from 0 to indefinite. The structs could be 1-Dimensional or multi-Dimensional.
Syntax:
struct_name = struct(‘Field_name_1’,
Value_1, ‘Field_name_2’, Value_2, …)
This command would create a structure of name struct_name and it’ll have as many values as given in the command arguments of the struct(). Every field has its own reference name to be called by.
Methods of Creating and Accessing Structures:
1. Creating a Structure With Fields:
To create a structure with given fields and values, one can use the following example:
Example 1:
Matlab
employees = struct( 'emp_ids' ,
[117, 119, 123], 'emp_names' ,
char( 'Mark' , 'John' , 'Sam' ),
'emp_age' , [27,29,33])
|
Output:
To hide this being displayed after every execution, add a ‘ ; ‘ at the end of the line to hide it.
2. To Display a Field:
Simply call the field name with the syntax <struct_name.field_name>. This would display the field’s values in the command window. Here is an example of the same:
Example 2:
Matlab
employees = struct( 'emp_ids' , [117, 119, 123],
'emp_names' , char( 'Mark' , 'John' , 'Sam' ),
'emp_age' , [27,29,33]);
employees.emp_ids
|
Output:
3. Adding a New Element in a Field:
To add new elements in a field, simply use the command as
<stuct_name.filename(index)=value>.
Example 3:
Matlab
employees = struct( 'emp_ids' , [117, 119, 123],
'emp_names' , char( 'Mark' , 'John' , 'Sam' ),
'emp_age' , [27,29,33]);
employees.emp_ids
employees.emp_ids(4)=129;
employees.emp_ids
|
Output:
The above script displays the emp_ids before and after adding 129 values to the list.
4. Creating an Empty Structure:
An empty structure i.e., a structure with no fields, could be created like
Output:
5. Creating Array of Structures:
MATLAB allows users to create arrays of structures. The syntax is simple.
arr_struct = [struct(), struct(), …]
This would create a 1-D array of n size, where n is number of structs.
Example 5:
Matlab
arr_struct = [struct( 'name' ,
char( 'John' ), 'age' , 29, 'id' , 119 );
struct( 'name' , char( 'Mark' ),
'age' , 27, 'id' , 117);];
arr_struct
|
Output:
However, it must be noted that every structure in the array must have the same field names because an array is a data collection of the same data type; in this case, the same struct type. Now one would access the structs in the array as an element of the array.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...