0
0
MATLABdata~5 mins

Structures and field access in MATLAB

Choose your learning style9 modes available
Introduction

Structures help you group related information together in one place. You can easily organize and access data by names instead of numbers.

You want to store information about a person like name, age, and height together.
You need to keep details of a book such as title, author, and year in one variable.
You want to organize sensor data with fields like temperature, humidity, and time.
You want to pass multiple related values to a function without using many separate variables.
Syntax
MATLAB
structName.fieldName = value;

Use dot . to access or create fields inside a structure.

You can create a structure by assigning values to fields directly.

Examples
This creates a structure person with fields name and age.
MATLAB
person.name = 'Alice';
person.age = 30;
Here, book is a structure holding information about a book.
MATLAB
book.title = 'Matlab Basics';
book.author = 'John';
book.year = 2023;
Structure data stores sensor readings.
MATLAB
data.temperature = 22.5;
data.humidity = 60;
Sample Program

This program creates a structure student with three fields and prints each field's value.

MATLAB
student.name = 'Bob';
student.age = 21;
student.grade = 'A';

% Display student information
fprintf('Name: %s\n', student.name);
fprintf('Age: %d\n', student.age);
fprintf('Grade: %s\n', student.grade);
OutputSuccess
Important Notes

You can add new fields anytime by assigning a value to a new field name.

Use isfield(structure, 'fieldName') to check if a field exists.

Structures can hold different types of data in each field, like numbers, text, or arrays.

Summary

Structures group related data using named fields.

Access fields with dot notation: structure.field.

Structures make your data organized and easy to use.