Access Data in Structure Array

This example shows how to access the contents of a structure array. To run the code in this example, load several variables into a structure named S.

Access Data in Scalar Structure

First, load data from flujet.mat into the scalar structure S. The file flujet.mat contains an image of a simulation of an astrophysical jet experiencing turbulence.

S = load('flujet.mat')
S = struct with fields:
          X: [400x300 double]
        map: [64x3 double]
    caption: [2x32 char]

The variables from the file (X, caption, and map) are now fields in the structure.

Access the data using dot notation of the form structName.fieldName. For example, pass the numeric data in field X to the image function:

image(S.X)
colormap(S.map)

To access part of a field, add indices as appropriate for the size and type of data in the field. For example, pass the center left section of X to the image function.

centerLeft = S.X(150:250,1:50);
image(centerLeft)

If a field contains a cell array, use curly braces to access the data, such as S.cellField{1:50,1:80}.

Access Data by Indexing into Structure Array

Create a nonscalar array by loading data from the file cape.mat into a second element of array S. The file cape.mat contains an image of Cape Cod, Massachusetts.

Each element of a structure array must have the same fields. Both flujet.mat and cape.mat contain variables X, map, and caption. S is a 1-by-2 array.

S(2) = load('cape.mat')
S=2×3 struct
    X
    map
    caption

For nonscalar structures, the syntax for accessing a field is structName(indices).fieldName. Display the image of Cape Cod, specifying 2 as the index into S.

image(S(2).X)
colormap(S(2).map)

Add indices to select and display a small section of S(2).X.

capeSection = S(2).X(200:300,150:250);
image(capeSection)

Note

You can index into part of a field only when you refer to a single element of a structure array. MATLAB® does not support statements such as S(1:2).X(1:50,1:80), which attempt to index into a field for multiple elements of the structure.

Related Topics