开发者

How to create a string array in MATLAB?

开发者 https://www.devze.com 2022-12-31 02:21 出处:网络
I would like to pass a vector of strings from C++ to MATLAB. I have tried using the functions available such as mxCreateCharMat开发者_Python百科rixFromStrings, but it doesn\'t give me the correct beha

I would like to pass a vector of strings from C++ to MATLAB. I have tried using the functions available such as mxCreateCharMat开发者_Python百科rixFromStrings, but it doesn't give me the correct behavior.

So, I have something like this:

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...

The problem is how do I get this vector to the matlab environment?

   plhs[0] = ???

My goal is to be able to run:

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


Storing a vector of strings as a char matrix requires that all of your strings are the same length and that they're stored contiguously in memory.

The best way to store an array of strings in MATLAB is with a cell array, try using mxCreateCellArray, mxSetCell, and mxGetCell. Under the hood, cell arrays are basically an array of pointers to other objects, char arrays, matrices, other cell arrays, etc..


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

精彩评论

暂无评论...
验证码 换一张
取 消