3

我想将字符串向量从 C++ 传递给 MATLAB。我曾尝试使用可用的功能,例如mxCreateCharMatrixFromStrings,但它没有给我正确的行为。

所以,我有这样的事情:

void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
   vector<string> stringVector;
   stringVector.push_back("string 1");
   stringVector.push_back("string 2");
   //etc...

问题是如何将这个向量放到 matlab 环境中?

   plhs[0] = ???

我的目标是能够运行:

>> [strings] = MyFunc(...)
>> strings(1) = 'string 1'
4

2 回答 2

5

将字符串向量存储为 char 矩阵要求所有字符串的长度相同,并且它们连续存储在内存中。

在 MATLAB 中存储字符串数组的最佳方法是使用元胞数组,尝试使用mxCreateCellArraymxSetCellmxGetCell。在底层,元胞数组基本上是指向其他对象、字符数组、矩阵、其他元胞数组等的指针数组。

于 2010-05-19T16:29:18.440 回答
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int rows = 5;
    vector<string> predictLabels;
    predictLabels.resize(rows);
    predictLabels.push_back("string 1");
    predictLabels.push_back("string 2");
    //etc...

    // "vector<string>" convert to  matlab "cell" type
    mxArray *arr = mxCreateCellMatrix(rows, 1);
    for (mwIndex i = 0; i<rows; i++) {
        mxArray *str = mxCreateString(predictLabels[i].c_str());
        mxSetCell(arr, i, mxDuplicateArray(str));
        mxDestroyArray(str);
    }
    plhs[0] = arr;
}
于 2019-03-27T03:54:31.417 回答