0
0
MATLABdata~5 mins

Structure arrays in MATLAB

Choose your learning style9 modes available
Introduction

Structure arrays let you group related data with different types in one variable. This helps organize information clearly.

When you want to store information about multiple people, like names, ages, and heights.
When you need to keep different types of data together, such as text and numbers for each item.
When you want to access data by names instead of just positions.
When you want to add new fields later without changing the whole data layout.
Syntax
MATLAB
structArray = struct('field1', {value1, value2, ...}, 'field2', {value1, value2, ...});

Each field holds data for all elements in the structure array.

Use curly braces {} to assign multiple values to fields for each element.

Examples
Creates a structure array with two elements. Each has a name and age.
MATLAB
people = struct('name', {'Alice', 'Bob'}, 'age', {25, 30});
Creates an empty structure array with fields but no elements.
MATLAB
emptyStruct = struct('name', {}, 'age', {});
Structure array with one element.
MATLAB
onePerson = struct('name', {'Charlie'}, 'age', {40});
Adds a third element to the existing structure array.
MATLAB
people(3).name = 'Diana'; people(3).age = 22;
Sample Program

This program creates a structure array with two people, shows it, adds a third person, and shows the updated array.

MATLAB
people = struct('name', {'Alice', 'Bob'}, 'age', {25, 30});
disp('Before adding new person:');
disp(people);

people(3).name = 'Charlie';
people(3).age = 40;

disp('After adding new person:');
disp(people);
OutputSuccess
Important Notes

Accessing fields is fast because data is organized by field names.

Adding elements at the end is easy, but inserting in the middle requires shifting elements.

Use structure arrays when you want to keep related but different types of data together.

Time complexity for adding an element at the end is O(1), but inserting in the middle is O(n).

Space complexity grows with the number of elements and fields.

Common mistake: Mixing cell arrays and structure arrays syntax can cause errors.

Summary

Structure arrays group related data with different types in one variable.

Use them to organize data by named fields for easy access.

You can add, access, and modify elements using field names and indices.