问题
I am trying to speeden up my Matlab program by writing a few functions in C++ and using the mex interface to integrate them. I got my results in a vector in c++. I want to transfer it to an array in MATLAB. I know i should redirect
plhs[0] to the vector
but i am not getting how exactly should I do it.
回答1:
When I've done similar things, I manually marshal the data so that it won't be freed when the C++ routine is completed. Here's a basic outline:
#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 that is a good starting point - you may want to inline it, but I'm not sure of the benefit. Btw, if you haven't checked out the matlab mex help, it is a great resource.
来源:https://stackoverflow.com/questions/9640738/mex-transferring-a-vector-from-c-to-matlab-from-mex-function