Search code examples
c++matlabstructmex

Set matrix field to Matlab struct


I am interfacing Matlab code with C++ code integrating engine.h.

I create a struct with several scalar and matrix fields. I create first the scalar fields using command line syntax, i wrote the helper method

void matlabSetStruct(Engine * ep, const std::string structure, 
                                            const std::string field, T value)
{
    ostringstream ss;
    ss << value;
    std::string setStruct = structure + "." + field + " = " + ss.str() + ";";
    matlabExecute(ep, setStruct);
}

now, I would like to add matrix fields to the same struct. I can successfully create new matrix variables with name MyStruct.Field but they are not recognized as fields of the existing struct MyStruct, but as new variables. I am using

int ret = engPutVariable(ep, array_name.c_str(), array);

If I whos, I get

  MyStruct                        1x1                 7176  struct              
  MyStruct.CT_F1                  1x1795             14360  double              
  MyStruct.CT_F2                  1x1795             14360  double    

--> matrix fields are independent variables

I found mxSetField, however this is for adding a field to a struct created with mxCreateStructMatrix and this method is for creating Matlab equivalent of a matrix of struct in C, not quite what I want to achieve.


Solution

  • One option is to create a temp variable, and then to assign its value to a field of the struct:

    // Create temp variable
    mxArray* array = convertVectorToMxArray(mat, nb_rows, nb_cols);  
    const std::string temp_name = array_name + "_temp";
    int ret = engPutVariable(ep, temp_name.c_str(), array);
    
    // Set variable to struct field
    const std::string cmd = std::string(array_name + " = " + temp_name + "; ");
    matlabExecute(ep, cmd);
    
    // Delete array
    mxDestroyArray(array);