Work with MATLAB Structure Arrays - MATLAB & Simulink (original) (raw)

In MATLABĀ®, you can create struct arrays by dynamically assigning field names and values. In contrast, C++ is a statically typed language that requires all fields of a struct and their types to be declared upfront. This discussion uses the exampleDeploy MATLAB Function That Accepts Struct Array as Input Argument to explain how to handle MATLAB structs in C++ code.

Struct Input

In MATLAB, struct arrays can be created by dynamically assigning field names and values. C++ being a statically typed language requires all fields of a struct and their types to be declared upfront.

When C++ code calls a MATLAB function that requires a MATLAB struct as input, the struct must be explicitly created in C++ using appropriate data types through the MATLAB Data API. For example:

% MATLAB data = struct(); data.temperatures = [72, 75, 69, 68, 70]; data.pressures = [30, 29.5, 30.2, 29.9, 30.1];
// C++ matlab::data::ArrayFactory factory; matlab::data::TypedArray temperatures = factory.createArray({ 5 }, { 72, 75, 69, 68, 70 }); matlab::data::TypedArray pressures = factory.createArray({ 5 }, { 30, 29.5, 30.2, 29.9, 30.1 }); matlab::data::StructArray inputStruct = factory.createStructArray({ 1 }, { "temperatures", "pressures" }); inputStruct[0]["temperatures"] = temperatures; inputStruct[0]["pressures"] = pressures;

Struct Output

When a MATLAB function called from C++ returns a MATLAB struct, it is returned as a matlab::data::Array in the C++ code. To retrieve the field names and field values, some processing is necessary. For example:

// Function to print the MATLAB computation results void printMatlabResults(matlab::data::Array outputArray) { matlab::data::StructArray structArray = outputArray; auto topLevelStructFieldNamesIterable = structArray.getFieldNames(); std::vectormatlab::data::MATLABFieldIdentifier topLevelStructFieldNames(topLevelStructFieldNamesIterable.begin(), topLevelStructFieldNamesIterable.end());

for (const matlab::data::MATLABFieldIdentifier& fieldName : topLevelStructFieldNames) {
    std::string outerFieldName(fieldName);
    std::cout << "Field: " << outerFieldName << std::endl;

    matlab::data::TypedArrayRef<matlab::data::Struct> nestedStruct = outputArray[0][fieldName];
    
    auto nestedStructFieldNamesIterable = nestedStruct.getFieldNames();
    std::vector<matlab::data::MATLABFieldIdentifier> 
        nestedStructFieldNames(nestedStructFieldNamesIterable.begin(), nestedStructFieldNamesIterable.end());
    for (const matlab::data::MATLABFieldIdentifier& fieldName : nestedStructFieldNames) {
        std::string innerFieldName(fieldName);
        matlab::data::TypedArrayRef<double> fieldValue = nestedStruct[0][fieldName];

        double value = fieldValue[0];
        std::cout << "  " << innerFieldName << ": " << std::fixed << std::setprecision(4) << value << std::endl;
    }
}

}

See Also

Topics