c++ - 在 C++ 代码中调用 Matlab - 使用 engine.h 中的方法

标签 c++ matlab matrix mex matlab-engine

我编写了一个 C++ 程序,其唯一目的是调用 Matlab 代码。我有一个主要例程,它

  1. 将文件中的数据(高维90000*24的矩阵)读入C++ 结构

  2. 将这些结构传递给 Matlab 代码

  3. 在参数中使用这些结构启动 Matlab 例程

  4. 从Matlab中获取输出数据并将其存储在C++结构中

在 2/中,矩阵是 Matlab 结构中的字段。结构,比如 MATLAB_STRUCT 有几个矩阵字段,MATLAB_STRUCT.Z1MATLAB_STRUCT.Z2,...和一些浮点字段 MATLAB_STRUCT .flt1,...

将 C++ 矩阵 (double**) 设置为 Matlab 结构的字段的正确方法是什么?到目前为止,我想出了这个,使用 engine.h

    mxArray* labcoeffs_array = convertVectorToMxArray(labcoeffs, 
                                                         coeff_nrows, coeff_ncols); 
    const std::string lab_coeff_name = "MATLAB_STRUCT.labCoef";
    engPutVariable(ep, lab_coeff_name.c_str(), labcoeffs_array);

其中 convertVectorToMxArray 是我编写的用于将 double** 转换为 mxArray 的助手,

inline mxArray *convertVectorToMxArray(double** mat, 
                                              const int nb_rows, const int nb_cols)
{
    mxArray *outputMxArray = mxCreateDoubleMatrix(
        (int) nb_rows,
        (int) nb_cols,
        mxREAL);

    double *data = (double*) mxGetData(outputMxArray);
    for (int r = 0; r < nb_rows; r++)
        for (int c = 0; c < nb_cols; c++)
            data[r + c*nb_rows] = (double)mat[r][c];

    return outputMxArray;
};

但我看到了一些其他技术,用于在 Cpp 代码中为 Matlab 结构赋值(虽然是浮点值,而不是矩阵),模仿 C++ 字符串中的命令行语法:

std::string setStruct = "MATLAB_STRUCT" + "." + "nB" + " = " + str->nB + ";";
matlabExecute(ep, setStruct);

ep 指向 Matlab 引擎的指针。

  • 是否可以通过命令行调整这种方法,以便为 Matlab 结构的矩阵类型字段赋值?

  • 为 Matlab 结构的矩阵类型字段赋值的最佳方法是什么?

最佳答案

这是一个类似于您所描述的虚构示例:

#include <iostream>
#include <vector>
#include "engine.h"

// create mxArray matrix from an array of data
mxArray* data_to_mxarray(const double *data, int nrows, int ncols)
{
    mxArray *arr = mxCreateDoubleMatrix(nrows, ncols, mxREAL);
    double *x = mxGetPr(arr);
    for (int c=0; c<ncols; c++) {
        for (int r=0; r<nrows; r++) {
            *x = data[r + c*nrows];
            x++;
        }
    }
    return arr;
}

int main()
{
    // step 1: some data
    const char *fieldnames[2] = {"z1", "z2"};
    double z1[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
    double z2[] = {7.0, 8.0, 9.0, 0.0, 1.0, 2.0};

    // open connection to MATLAB
    Engine *ep = engOpen("");

    // create structure with desired fields
    mxArray *st = mxCreateStructMatrix(1, 1, 2, fieldnames);
    mxSetField(st, 0, "z1", data_to_mxarray(z1,2,3));
    mxSetField(st, 0, "z2", data_to_mxarray(z2,3,2));

    // step 2: pass struct to MATLAB workspace
    engPutVariable(ep, "st", st);

    // for the sake of this example, lets create a fake function
    engEvalString(ep, "my_function = @(x) magic(3);");

    // step 3: call some function with the struct as input
    engEvalString(ep, "out = my_function(st);");

    // step 4: retrieve function output
    mxArray *out = engGetVariable(ep, "out");

    // extract data out of it. This depends on the type of output.
    // Say the result was a numeric array
    double *x = mxGetPr(out);
    size_t len = mxGetNumberOfElements(out);
    std::vector<double> v;
    v.resize(len);
    v.assign(x, x+len);
    for (int i=0; i<v.size(); i++) {
        std::cout << v[i] << std::endl;
    }

    // cleanup
    mxDestroyArray(out);
    mxDestroyArray(st);
    engClose(ep);

    return 0;
}

关于c++ - 在 C++ 代码中调用 Matlab - 使用 engine.h 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26774830/

相关文章:

matlab - 如何在 Matlab/Octave 中访问单个矩阵元素?

python - 如何在 numpy 和 R 之间传递大型数组?

c++ - 使用 winsock.h 的库问题

C++ 在文件中存储对象

c++ - Visual Studio - 程序在分析时运行得更快

带有句柄类的 Matlab Arrayfun

c++ - Windows 客户端应用程序使用 GSSAPI/Kerberos API 通过 KDC 进行身份验证

matlab - 合并不同单元格的元素

matlab - 如何创建十字交叉对角矩阵

python - np.multiply 如何工作?