Next: , Previous: Structure Arrays, Up: Structures


6.1.3 Creating Structures

Besides the index operator ".", Octave can use dynamic naming "(var)" or the struct function to create structures. Dynamic naming uses the string value of a variable as the field name. For example:

     a = "field2";
     x.a = 1;
     x.(a) = 2;
     x
          ⇒ x =
             {
               a =  1
               field2 =  2
             }

More realistically, all of the functions that operate on strings can be used to build the correct field name before it is entered into the data structure.

     names = ["Bill"; "Mary"; "John"];
     ages  = [37; 26; 31];
     for i = 1:rows (names)
       database.(names(i,:)) = ages(i);
     endfor
     database
          ⇒ database =
             {
               Bill =  37
               Mary =  26
               John =  31
             }

The third way to create structures is the struct command. struct takes pairs of arguments, where the first argument in the pair is the fieldname to include in the structure and the second is a scalar or cell array, representing the values to include in the structure or structure array. For example:

     struct ("field1", 1, "field2", 2)
     ⇒ ans =
           {
             field1 =  1
             field2 =  2
           }

If the values passed to struct are a mix of scalar and cell arrays, then the scalar arguments are expanded to create a structure array with a consistent dimension. For example:

     s = struct ("field1", {1, "one"}, "field2", {2, "two"},
             "field3", 3);
     s.field1
          ⇒
             ans =  1
             ans = one
     
     s.field2
          ⇒
             ans =  2
             ans = two
     
     s.field3
          ⇒
             ans =  3
             ans =  3

If you want to create a struct which contains a cell array as an individual field, you must wrap it in another cell array as shown in the following example:

     struct ("field1", {{1, "one"}}, "field2", 2)
          ⇒ ans =
             {
               field1 =
     
             {
               [1,1] =  1
               [1,2] = one
             }
     
               field2 =  2
             }

— Built-in Function: struct ("field", value, "field", value, ...)

Create a structure and initialize its value.

If the values are cell arrays, create a structure array and initialize its values. The dimensions of each cell array of values must match. Singleton cells and non-cell values are repeated so that they fill the entire array. If the cells are empty, create an empty structure array with the specified field names.

If the argument is an object, return the underlying struct.

The function isstruct can be used to test if an object is a structure or a structure array.

— Built-in Function: isstruct (x)

Return true if x is a structure or a structure array.

See also: ismatrix, iscell, isa.