Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a string array in MATLAB?

Tags:

c++

matlab

mex

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'
like image 532
aduric Avatar asked Apr 10 '26 06:04

aduric


1 Answers

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

like image 162
gtownescapee Avatar answered Apr 12 '26 19:04

gtownescapee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!