3

I would like to pass a vector of strings from C++ to MATLAB. I have tried using the functions available such as mxCreateCharMatrixFromStrings, 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'

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
Why mxDuplicateArray ? If you do mxSetCell(arr, i, str);, you can also remove mxDestroyArray(str);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.