| 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.
mwArray A;
A = struct_func("name", // field name
"John", // value
"number", // field name
311); // value
cout << A << endl;
This code produces the following output:
name:'John'number: 311
Note
The struct_func() routine defines the fields and their values in a single instance of a structure. To create an array of structures, use MATLAB indexing syntax in the assignment statement, as described in Using Assignment to Create Structures. |
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().
mwArray C,F,S;
// create cell array to be converted
C = cellhcat("tree",
37.4,
"birch");
cout << C << endl;
// create cell array of field names
F = cellhcat("category",
"height",
"name");
// convert cell array to structure
S = cell2struct(C,F,2);
cout << S << endl;
This code generates the following output:
'tree'[37.4000]'birch'category:'tree'height: 37.4000 name:'birch'
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).
mwArray S;
// Create array of structures by assignment
S(3) = struct_func("Name", // Field name
"Jim", // Value
"Number", // Field name
312); // Value
cout << S << endl;
This code generates the following output:
1x3 struct array with fields Name Number
For more detailed information about using indexing, see Chapter 4.
| MATLAB Structures | Performing Common Array Programming Tasks | ![]() |