Using the C++ Math Library    

Creating Structures

The MATLAB C++ Math Library allows you to create structures by:

Using a Structure Creation Routine

You can create a structure using the struct_func() routine. This routine lets you define the fields in the structure and assign a value to each field. For example, the following code fragment creates a structure that contains two fields, a text string and a scalar value.

This code produces the following output:

Using a Structure Conversion Routine

You can also create structures by converting an existing MATLAB cell array into a structure, using the cell2struct() routine. When converting a cell array into a structure, you must create a separate cell array that contains the names you want to assign to fields in the structure.

The following code fragment creates a cell array, C, containing data and a second cell array, F, containing field names. The example then passes these cell arrays to cell2Struct().

This code generates the following output:

Using Assignment to Create Structures

As with other MATLAB arrays, if you assign values to fields in a structure that is in an array of structures, the MATLAB C++ Math Library creates an array of structures large enough to accommodate the location specified by the index string.

The following example defines a structure with two fields, name and number. Because it is an indexed assignment statement, the library creates an array of 3 of these structures, assigning values to the third structure in the array. The first two structures in the array are initialized to contain empty arrays for each field. This C++ code is equivalent to the MATLAB statement,
S(2) = struct('name','jim','number',312).

This code generates the following output:

For more detailed information about using indexing, see Chapter 4.


 MATLAB Structures Performing Common Array Programming Tasks