BudiBadu Logo
Samplebadu

MATLAB by Example: Structures

R2023b

Structures (structs) allow you to group related data using named fields. This sample shows creation and access.

Code

% Creating a struct using dot notation
student.name = 'John Doe';
student.id = 12345;
student.grades = [85, 90, 92];

% Creating a struct using the struct() function
car = struct('make', 'Toyota', 'model', 'Camry', 'year', 2022);

% Array of structures
class(1).name = 'Alice';
class(1).score = 95;
class(2).name = 'Bob';
class(2).score = 88;

% Accessing data
avg_grade = mean(student.grades);
fprintf('%s got %.1f\n', student.name, avg_grade);

Explanation

Structures, or "structs", are data types that group related data into containers called fields. Each field has a name and contains data of any type. You can create a struct simply by assigning a value to a field using dot notation, like student.name = 'John'. If the struct student didn't exist, MATLAB creates it automatically.

Alternatively, you can use the struct function to create a structure in one line. This is useful for initializing structures with specific values. You can also create arrays of structures, where each element of the array is a struct with the same fields. This is similar to a list of objects in other languages.

Structs are excellent for organizing complex data. For example, instead of having separate variables for sensor_data, sensor_time, and sensor_location, you can group them into a single sensor struct. This makes passing data to functions much cleaner, as you only need to pass one variable.

Code Breakdown

2
student.name = ... dynamically adds the field 'name' to the struct 'student'.
10
class(1).name = ... creates a struct array. All elements in the array will have the same fields.