mex从mex函数将向量从c ++传输到matlab [英] mex transferring a vector from c++ to matlab from mex function
问题描述
我试图通过用C ++编写一些函数并使用mex接口集成它们来加速我的Matlab程序.我在c ++中的向量中得到了结果.我想将其传输到MATLAB中的数组. 我知道我应该重定向
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.
推荐答案
完成类似操作后,我将手动封送数据,以免C ++例程完成后将其释放.这是一个基本轮廓:
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);
}
如果我将其另存为test.cpp
,然后在该目录中打开matlab,则请执行以下操作:
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
这是预期的输出.希望这是一个很好的起点-您可能需要内联它,但是我不确定这样做的好处.顺便说一句,如果您还没有签出 matx mex帮助,那真是太棒了资源.
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.
这篇关于mex从mex函数将向量从c ++传输到matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!