Next: , Up: Data Structures


6.1.1 Structure Arrays

A structure array is a particular instance of a structure, where each of the fields of the structure is represented by a cell array. Each of these cell arrays has the same dimensions. An example of the creation of a structure array is

     x(1).a = "string1"
     x(2).a = "string2"
     x(1).b = 1
     x(2).b = 2

which creates a 2-by-1 structure array with two fields. As previously, to print the value of the structure array, you can type its name:

     octave:1> x
     x =
     {
       1x2 struct array containing the fields:
     
         a
         b
     }

Individual elements of the structure array can be returned by indexing the variable like x (1), which returns a structure with the two fields like

     octave:2> x(1)
     ans =
     {
       a = string1
       b =  1
     }

Furthermore, the structure array can return a comma separated list (see Comma Separated Lists), if indexed by one of its own field names. For example

     octave:3> x.a
     ans = string1
     ans = string2

Here is another example, using this comma separated list on the left-hand side of an assignment:

     octave:4> [x.a] = deal("new string1", "new string2");
     octave:5> x(1).a
     ans = new string1
     octave:6> x(2).a
     ans = new string2

Just as for numerical arrays, it is possible to use vectors as indices (see Index Expressions):

     octave:7> x(3:4) = x(1:2);
     octave:8> [x([1,3]).a] = deal("other string1", "other string2");
     octave:9> x.a
     ans = other string1
     ans = new string2
     ans = other string2
     ans = new string2

The function size will return the size of the structure. For the example above

     octave:10> size(x)
     ans =
     
        1   4

Elements can be deleted from a structure array in a similar manner to a numerical array, by assigning the elements to an empty matrix. For example

     in = struct ("call1", {x, Inf, "last"},
                  "call2", {x, Inf, "first"});
     in (1, :) = []
     ⇒ in =
           {
             call1 =
     
             (,
               [1] = Inf
               [2] = last
             ,)
     
             call2 =
     
             (,
               [1] = Inf
               [2] = first
             ,)
     
           }