如何在MATLAB中创建一个字符串数组?

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'
2个回答

5

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

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


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;
}

2
虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并指出适用的限制和假设。 - Pika Supports Ukraine
为什么要使用mxDuplicateArray?如果你使用mxSetCell(arr, i, str);,你也可以移除mxDestroyArray(str); - Cris Luengo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接