MATLAB Programming/Struct Arrays

From Wikibooks, open books for an open world
< MATLAB Programming
Jump to: navigation, search

Contents

[edit] Introduction to Structures

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.

[edit] Declaring Structures

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 =
     b: 0
     c: 'test'

Structures can be declared as needed and so can the fields.

[edit] Arrays of Structures

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'

[edit] Accessing Fields

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
         

[edit] Accessing Array Elements

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'}

[edit] External Resources

ControlTheoryPro.com