Documentation Center

  • Trial Software
  • Product Updates

Access Data in a 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 scalar (1-by-1) structure named S.

S = load('clown.mat')
S = 

          X: [200x320 double]
        map: [81x3 double]
    caption: [2x1 char]

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

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 upper left corner of X to the image function:

upperLeft = S.X(1:50,1:80);
image(upperLeft);

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

Data in Nonscalar Structure Arrays

Create a nonscalar array by loading data from the file mandrill.mat into a second element of array S:

 S(2) = load('mandrill.mat')

Each element of a structure array must have the same fields. Both clown.mat and mandrill.mat contain variables X, map, and caption.

S is a 1-by-2 array.

S = 
1x2 struct array with fields:
    X
    map
    caption

For nonscalar structures, the syntax for accessing a particular field is structName(indices).fieldName. Redisplay the clown image, specifying the index for the clown struct (1):

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

Add indices to select and redisplay the upper left corner of the field contents:

upperLeft = S(1).X(1:50,1:80);
image(upperLeft)

    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 Information

Was this topic helpful?