| Contents | Index |
| On this page… |
|---|
Access Data in a Structure Array Generate Field Names from Variables Access Data in Nested Structures Access Multiple Elements of a Nonscalar Struct Array |
This example shows how to create a structure array. A structure is a data type that groups related data using data containers called fields. Each field can contain data of any type or size.
Store a patient record in a scalar structure with fields name, billing, and test.

patient.name = 'John Doe';
patient.billing = 127.00;
patient.test = [79, 75, 73; 180, 178, 177.5; 172, 170, 169];
patient
patient =
name: 'John Doe'
billing: 127
test: [3x3 double]
Add records for other patients to the array by including subscripts after the array name.

patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
patient
patient =
1x2 struct array with fields:
name
billing
test
Each patient record in the array is a structure of class struct. An array of structures is often referred to as a struct array. Like other MATLAB arrays, a struct array can have any dimensions.
A struct array has the following properties:
All structs in the array have the same number of fields.
All structs have the same field names.
Fields of the same name in different structs can contain different types or sizes of data.
Any unspecified fields for new structs in the array contain empty arrays.
patient(3).name = 'New Name';
patient(3)
ans =
name: 'New Name'
billing: []
test: []
Access data in the structure array to find how much the first patient owes, and to create a bar graph of his test results.
amount_due = patient(1).billing
bar(patient(1).test)
title(['Test Results for ', patient(1).name])
amount_due = 127

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')The variables from the file (X, caption, and map) are now fields in the struct.
S =
X: [200x320 double]
map: [81x3 double]
caption: [2x1 char]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
captionFor 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
This example shows how to concatenate structure arrays using the [] operator. To concatenate structures, they must have the same set of fields, but the fields do not need to contain the same sizes or types of data.
Create scalar (1-by-1) structure arrays struct1 and struct2, each with fields a and b:
struct1.a = 'first'; struct1.b = [1,2,3]; struct2.a = 'second'; struct2.b = rand(5);
Just as concatenating two scalar values such as [1, 2] creates a 1-by-2 numeric array, concatenating struct1 and struct2,
combined = [struct1, struct2]
creates a 1-by-2 structure array:
combined =
1x2 struct array with fields:
a
bWhen you want to access the contents of a particular field, specify the index of the structure in the array. For example, access field a of the first structure:
combined(1).a
This code returns
ans = first
Concatenation also applies to nonscalar structure arrays. For example, create a 2-by-2 structure array named new:
new(1,1).a = 1; new(1,1).b = 10; new(1,2).a = 2; new(1,2).b = 20; new(2,1).a = 3; new(2,1).b = 30; new(2,2).a = 4; new(2,2).b = 40;
Because the 1-by-2 structure combined and the 2-by-2 structure new both have two columns, you can concatenate them vertically with a semicolon separator:
larger = [combined; new]
This code returns a 3-by-2 structure array,
larger =
3x2 struct array with fields:
a
bwhere, for example,
larger(2,1).a =
1For related information, see:
This example shows how to derive a field name at run time from a variable or expression. The general syntax is
structName.(dynamicExpression)
where dynamicExpression is a variable or expression that returns a character or string. Field names that you reference with expressions are called dynamic field names.
For example, create a field name from the current date:
currentDate = datestr(now,'mmmdd');
myStruct.(currentDate) = [1,2,3]If the current date reported by your system is February 29, then this code assigns data to a field named Feb29:
myStruct =
Feb29: [1 2 3]Field names, like variable names, must begin with a letter, can contain letters, digits, or underscore characters, and are case sensitive. To avoid potential conflicts, do not use the names of existing variables or functions as field names. For more information, see Valid Variable Names.
This example shows how to index into a structure that is nested within another structure. The general syntax is
structName(indices).nestedStructName.(indices).fieldName(indices)
When a structure is scalar (1-by-1), you do not need to include the indices to refer to the single element. For example, create a scalar structure s, where field n is a nested scalar structure with fields a, b, and c:
s.n.a = ones(3); s.n.b = eye(4); s.n.c = magic(5);
Access the third row of field b:
third_row_b = s.n.b(3,:)
Variable third_row_b contains the third row of eye(4).
third_row_b =
0 0 1 0Expand s so that both s and n are nonscalar (1-by-2):
s(1).n(2).a = 2 * ones(3); s(1).n(2).b = 2 * eye(4); s(1).n(2).c = 2 * magic(5); s(2).n(1).a = '1a'; s(2).n(2).a = '2a'; s(2).n(1).b = '1b'; s(2).n(2).b = '2b'; s(2).n(1).c = '1c'; s(2).n(2).c = '2c';
Structure s now contains the data shown in the following figure.

Access part of the array in field b of the second element in n within the first element of s:
part_two_eye = s(1).n(2).b(1:2,1:2)
This returns the 2-by-2 upper left corner of 2 * eye(4):
part_two_eye =
2 0
0 2This 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
s(1:3).f
or
s.f
MATLAB returns the data from the elements in a comma-separated list, which displays as follows:
ans =
1
ans =
two
ans =
3 3 3
3 3 3
3 3 3You 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 3If 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 struct 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 9For related information, see:
There are at least two ways you can organize data in a structure array: plane organization and element-by-element organization. The method that best fits your data depends on how you plan to access the data, and, for very large data sets, whether you have system memory constraints.
Plane organization allows easier access to all values within a field. Element-by-element organization allows easier access to all information related to a single element or record. The following sections include an example of each type of organization:
When you create a structure array, MATLAB stores information about each element and field in the array header. As a result, structures with more elements and fields require more memory than simpler structures that contain the same data. For more information on memory requirements for arrays, see Memory Allocation.
Consider an RGB image with three arrays corresponding to color intensity values.

If you have arrays RED, GREEN, and BLUE in your workspace, then these commands create a scalar structure named img that uses plane organization:
img.red = RED; img.green = GREEN; img.blue = BLUE;
Plane organization allows you to easily extract entire image planes for display, filtering, or other processing. For example, multiply the red intensity values by 0.9:
adjustedRed = .9 * img.red;
If you have multiple images, you can add them to the img structure, so that each element img(1),...,img(n) contains an entire image. For an example that adds elements to a structure, see the following section.
Consider a database with patient information. Each record contains data for the patient's name, test results, and billing amount.

These statements create an element in a structure array named patient:
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];Additional patients correspond to new elements in the structure. For example, add an element for a second patient:
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];Element-by-element organization supports simple indexing to access data for a particular patient. For example, find the average of the first patient's test results, calculating by rows (dimension 2) rather than by columns:
aveResultsDoe = mean(patient(1).test,2)
This code returns
aveResultsDoe = 75.6667 178.5000 212.0000
For information on processing data from more than one element at a time, see Access Data in a Structure Array.
Structure arrays do not require completely contiguous memory. However, each field requires contiguous memory, as does the header that MATLAB creates to describe the array. For very large arrays, incrementally increasing the number of fields or the number of elements in a field results in Out of Memory errors.
Allocate memory for the contents by assigning initial values with the struct function, such as
newStruct(1:25,1:50) = struct('a',ones(20),'b',zeros(30),'c',rand(40));
This code creates and populates a 25-by-50 structure array S with fields a, b, and c.
If you prefer not to assign initial values, you can initialize a structure array by assigning empty arrays to each field of the last element in the structure array, such as
newStruct(25,50).a = []; newStruct(25,50).b = []; newStruct(25,50).c = [];
or, equivalently,
newStruct(25,50) = struct('a',[],'b',[],'c',[]);
However, in this case, MATLAB only allocates memory for the header, and not for the contents of the array.
For more information, see:
![]() | Characters and Strings | Cell Arrays | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |