# Mex transferring a vector from C ++ to matlab from a mex function

I am trying to speed up my Matlab program by writing several functions in C ++ and using the mex interface to integrate them. I got my results in a vector in C ++. I want to pass it to an array in MATLAB. I know that I have to redirect

` plhs[0] to the vector `

but i am not getting how exactly should I do it.
+3

source to share

1 answer

When I did things like this, I manually sorted the data so that it doesn't get freed when the C ++ procedure ends. Here's a basic plan:

```
#include <vector>
#include "mex.h"
mxArray * getMexArray(const std::vector<double>& v){
mxArray * mx = mxCreateDoubleMatrix(1,v.size(), mxREAL);
std::copy(v.begin(), v.end(), mxGetPr(mx));
return mx;
}
void mexFunction(int nlhs, mxArray *plhs[ ], int nrhs, const mxArray *prhs[ ]) {
std::vector<double> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);
plhs[0] = getMexArray(v);
}
```

If I save this as `test.cpp`

and then open matlab in that directory, I do the following:

```
>> mex test.cpp
>> test
ans =
0 1 2 3
```

which is the expected output. Hopefully this is a good starting point - you might want to embed it, but I'm not sure about that. Btw, if you haven't checked out the help on using matlab mex this is a great resource.

+6

source to share