【问题标题】:How to create a string array in MATLAB?如何在 MATLAB 中创建字符串数组?
【发布时间】:2010-05-19 16:11:32
【问题描述】:

我想将字符串向量从 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'

【问题讨论】:

    标签: c++ matlab mex


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      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;
      }
      

      【讨论】:

      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。
      • 为什么是mxDuplicateArray ?如果你做mxSetCell(arr, i, str);,你也可以删除mxDestroyArray(str);
      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多