Main Content

Access Elements of a Nonscalar Structure Array

This example shows how to access and process data from multiple elements of a nonscalar structure array:

Create a 1-by-3 structure s with field f:

s(1).f = 1;
s(2).f = 'two';
s(3).f = 3 * ones(3);

Although each structure in the array must have the same number of fields and the same field names, the contents of the fields can be different types and sizes. When you refer to field f for multiple elements of the structure array, such as




MATLAB® returns the data from the elements in a comma-separated list, which displays as follows:

ans =

ans =

ans =
     3     3     3
     3     3     3
     3     3     3

You cannot assign the list to a single variable with the syntax v = s.f because the fields can contain different types of data. However, you can assign the list items to the same number of variables, such as

[v1, v2, v3] = s.f;

or assign to elements of a cell array, such as

c = {s.f};

If all of the fields contain the same type of data and can form a hyperrectangle, you can concatenate the list items. For example, create a structure nums with scalar numeric values in field f, and concatenate the data from the fields:

nums(1).f = 1;
nums(2).f = 2;
nums(3).f = 3;

allNums = [nums.f]

This code returns

allNums =
     1     2     3

If you want to process each element of an array with the same operation, use the arrayfun function. For example, count the number of elements in field f of each structure in array s:

numElements = arrayfun(@(x) numel(x.f), s)

The syntax @(x) creates an anonymous function. This code calls the numel function for each element of array s, such as numel(s(1).f), and returns

numElements =
     1     3     9

For related information, see: