A struct array is a data type that uses named containers called “fields” to store data of varying types and sizes.

Dot notation

Use the dot notation to specify the fields of a new struct array.

``````% Struct array with fields 'name' and 'sex'
array1(1).name = 'Peter Pan';
array1(1).sex = 'M';``````

struct function

Use the `struct` function to create a struct array with the specified fields and values. Note that arguments are passed in the form `field1`, `value1`, `…`, `fieldN`, `valueN`.

``array2 = struct('name', 'Peter Pan', 'sex', 'M');``

To create a struct array having multiple elements, use cell arrays to group field values, and call the `struct` function. The cell arrays must have the same size and this size determines the shape of the struct array.

``````names = {'Peter Pan','Wendy Darling'};
sexes = {'M','F'};
array3 = struct('name', names, 'sex', sexes);``````

If the value of a field is the same for all elements and is not a nonscalar cell array, pass it directly.

``````% Field 'sex' is empty in all elements
array4 = struct('name', names, 'sex', '');``````

I recommend the following books to learn more on struct arrays in MATLAB:

1. This book was the winner of a Textbook Excellence Award. Struct arrays, cell arrays, and other data types, are explained clearly in the eighth chapter.

2. MATLAB for Engineers (5th Edition)

This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 11 explains excellently struct arrays, cell arrays, and character arrays, among other data types.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

``doc struct;``

Exercise

A Minimum Bounding Box (MBR) is the minimum rectangle that encloses a group of pixels. MBRs are usually defined by the location of the upper-left corner, a width, and a height.

Store in a struct array the MBRs specified in Table 1. Column headers indicate field names.

Table 1. Listing of minimum bounding boxes.
label xorigin yorigin width height
MBR1 0 0 10 5
MBR2 10 5 7 8
MBR3 7 9 3 6

Source code

I hope you have learned how to create struct arrays in MATLAB. The source code developed in this tutorial is available at this page.