MATLAB - Structures
MATLAB - Structures
Section titled “MATLAB - Structures”In MATLAB, a structure is a data type that groups related data using named containers called fields. Each field can hold any type of data, such as a number, a string, a matrix, or even another structure. This makes structures ideal for organizing complex, heterogeneous data, such as a patient record or an experiment’s parameters.
A structure array is an array where each element is a structure of the same format (i.e., having the same field names). This is incredibly useful for managing collections of similar items, like a list of students or a catalog of products.
Creating Structures
Section titled “Creating Structures”You can create structures in two primary ways: using dot notation or the struct function.
1. Using Dot Notation
Section titled “1. Using Dot Notation”Dot notation is the most intuitive way to create a single structure or add fields to an existing one. You simply assign a value to a field using the syntax structName.fieldName = value;.
% Create a structure to store information about one studentstudent.name = 'John Doe';student.id = 12345;student.courses = {'Calculus', 'Physics', 'History'};student.grades = [85, 92, 78];
% Display the created structuredisp(student);When you execute this code, MATLAB displays the structure and its contents:
struct with fields:
name: 'John Doe' id: 12345 courses: {'Calculus', 'Physics', 'History'} grades: [85 92 78]2. Using the struct Function
Section titled “2. Using the struct Function”The struct function is ideal for creating a structure array from existing cell arrays or matrices. It is particularly efficient for pre-allocating structure arrays.
Syntax
Section titled “Syntax”s = struct(field1, value1, field2, value2, ...)Here, fieldN is a character vector (e.g., 'Name') and valueN is typically a cell array of values for that field across all elements of the structure array.
Example: Creating a Structure Array of Students
Section titled “Example: Creating a Structure Array of Students”% Define data in cell arraysnames = {'Riya', 'Tiya', 'Siya'};ids = {101, 102, 103};majors = {'Engineering', 'Arts', 'Science'};
% Create a 1x3 structure arraystudents = struct('Name', names, 'ID', ids, 'Major', majors);
% Access data for the second studentriyas_major = students(1).Major;disp(riyas_major)
% Display the entire structure arraydisp(students);Output:
Engineering
1x3 struct array with fields:
Name ID MajorYou can inspect an individual element, for example students(2), to see its contents:
students(2)
ans =
struct with fields:
Name: 'Tiya' ID: 102 Major: 'Arts'Working with Structures and Structure Arrays
Section titled “Working with Structures and Structure Arrays”MATLAB provides several functions to manage and inspect structures.
| Function | Description |
|---|---|
| fieldnames(S) | Returns a cell array of strings containing the names of the fields in structure S. |
| isfield(S, fieldName) | Checks if fieldName (a string) is a field in structure S. Returns logical true (1) or false (0). |
| isstruct(A) | Determines if the variable A is a MATLAB structure. Returns true or false. |
| rmfield(S, fieldName) | Removes the specified field fieldName from structure S and returns the modified structure. |
Example: Using Structure Functions
Section titled “Example: Using Structure Functions”% Re-use the 'students' structure array from the previous examplenames = {'Riya', 'Tiya', 'Siya'};ids = {101, 102, 103};majors = {'Engineering', 'Arts', 'Science'};students = struct('Name', names, 'ID', ids, 'Major', majors);
% 1. Get all field namesf_names = fieldnames(students);disp('Field names:');disp(f_names);
% 2. Check if 'ID' is a field (should be true)has_id = isfield(students, 'ID');disp(['Does struct have ''ID'' field? ', num2str(has_id)]);
% 3. Check if 'GPA' is a field (should be false)has_gpa = isfield(students, 'GPA');disp(['Does struct have ''GPA'' field? ', num2str(has_gpa)]);
% 4. Check if 'students' is a structureis_a_struct = isstruct(students);disp(['Is the variable a struct? ', num2str(is_a_struct)]);
% 5. Remove the 'Major' fieldstudents_modified = rmfield(students, 'Major');disp('Structure after removing ''Major'' field:');disp(students_modified);Output:
Field names: 'Name' 'ID' 'Major'
Does struct have 'ID' field? 1Does struct have 'GPA' field? 0Is the variable a struct? 1Structure after removing 'Major' field: 1x3 struct array with fields:
Name IDBest Practice: Structures vs. Tables
Section titled “Best Practice: Structures vs. Tables”For handling tabular data (where each row is an observation and each column is a variable), MATLAB’s table data type is often a more powerful and convenient alternative to a structure array. Tables offer column-based operations, metadata support, and seamless integration with statistical and plotting functions. Consider using a table when your data fits a spreadsheet-like format.