MATLAB Programming/Struct Arrays
Contents |
Introduction to Structures [edit]
MATLAB provides a means for structure data elements. Structures are created and accessed in a manner familiar for those accustomed to programming in C.
MATLAB has multiple ways of defining and accessing structure fields. See Declaring Structures for more details.
Note: Structure field names must begin with a letter, and are case-sensitive. The rest of the name may contain letters, numerals, and underscore characters. Use the namelengthmax function to determine the maximum length of a field name.
Declaring Structures [edit]
Structures can be declared using the struct command.
>> a = struct('b', 0, 'c', 'test')
a =
b: 0
c: 'test'
In MATLAB, variables do not require explicit declaration before their use. As a result structures can be declared with the '.' operator.
>> b.c = 'test'
b =
c: 'test'
Structures can be declared as needed and so can the fields.
Arrays of Structures [edit]
Structures can also be arrays. Below is an example
>> a = struct('b', 0, 'c', 'test'); % Create structure
>> a(2).b = 1; % Turn it into an array by creating another element
>> a(2).c = 'testing'
a =
1x2 struct array with fields:
b
c
>> a(1) % Initial structure
ans =
b: 0
c: 'test'
>> a(2) % The second element
ans =
b: 1
c: 'testing'
Accessing Fields [edit]
When the field name is known the field value can be accessed directly.
>> a.c
ans =
test
ans =
testing
In some cases you may need to access the field dynamically which can be done as follows.
>> str = 'c';
>> a(1).(str)
ans =
test
>> a(1).c
ans =
test
Accessing Array Elements [edit]
Any given element in a structure array can be accessed through an array index like this
>> a(1).c
ans =
test
To access all elements in a structure array use the syntax {structure.field}. In order to get all values in a vector or array use square brackets ([]) as seen below.
>> [a.('c')]
ans =
testtesting
>> [a.('b')]
ans =
0 1
Or you can put them all into a cell array (rather than concatenating them) like this:
>> {a.('c')}
ans = {'test', 'testing'}
This page may need to be