如何将结构字段从 Matlab 加载到 C++?

How can I load struct fields from Matlab to C++?

所以我有一个名为 stf 的结构,其中包含多个字段;每个字段都是一个向量。我尝试使用 Matio 库来访问这些变量,但我得到的只是一个变量,即结构 stf。由于 stf 结构有 4 个字段,我得到 4 个 double 变量。但是我如何访问字段本身呢?我想在我的 C++ 代码中将这些字段中的每一个存储在一个向量中。

为了更好地理解,这是我的代码:

int main(int argc, char** argv)
{
    mat_t* matfp;
    matvar_t* matvar;
    matfp = Mat_Open("fields.mat", MAT_ACC_RDONLY);
    if (NULL == matfp) {
        fprintf(stderr, "Error opening MAT file \"%s\"!\n", argv[1]);
        return EXIT_FAILURE;
    }
    matvar = Mat_VarRead(matfp, "stf");
    const double* xData = static_cast<const double*>(matvar->data);
    unsigned Size = matvar->nbytes / matvar->data_size;
    std::cout << "\n";
    for (int i = 0; i < matvar->rank; ++i)
    {
        std::cout << "\tdim[" << i << "] == " << matvar->dims[i] << "\n";
    }
    for (int i = 0; i < Size; ++i)
    {
        cout << "\tstf[" << i << "] = " << xData[i] << "\n";
    }

    Mat_Close(matfp);
    return EXIT_SUCCESS;
}

这是我得到的输出:

      dim[0] == 1
      dim[1] == 1
      stf[0] = 1.3315e-311
      stf[1] = 1.3315e-311
      stf[2] = 1.3315e-311
      stf[3] = 1.3315e-311

为什么它们都是相同的数字?我实在是不知所措,如有任何帮助,我们将不胜感激。

好的,我明白了。我创建了一个函数来加载结构字段,然后将它们存储在 Eigen 库中的矩阵中。它看起来像这样:

MatrixXd load(string workspace_name, const char* variable_name, const char* field_name)
{
    const char* filename = workspace_name.c_str();
    mat_t* mat;
    matvar_t* matvar, * field;
    mat = Mat_Open(filename, MAT_ACC_RDONLY);
    matvar = Mat_VarReadInfo(mat, variable_name);
    field = Mat_VarGetStructFieldByName(matvar, field_name, 0);
    int read_err = Mat_VarReadDataAll(mat, field);
    MatrixXd C;
    C.resize(field->dims[0], field->dims[1]);
    unsigned Size = field->nbytes / field->data_size;
    const double* Data = static_cast<const double*>(field->data);
    int column = 0;
    int row = 0;
    for (int i = 0; i < Size; ++i)
    {
        if (row > C.rows() - 1) {
            row = 0;
            column += 1;
        }
        C(row, column) = Data[i];
        row += 1;
    }

    Mat_VarFree(matvar);
    Mat_Close(mat);

    return C;
}