This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Best Practice for Calling an Eigen MEX function from Matlab

Tags: None
(comma "," separated)
mhughes
Registered Member
Posts
1
Karma
0
Hi All,

I'm hoping to use Eigen to help speed up some computations in Matlab. In particular, I'm writing a mex function

[Z,Mu] = MyMexFunction( X );

that takes in a matrix X, and returns two new matrices, Z and Mu. These matrices will be very big in some cases.

X has size N x D, with N = tens of thousands and D = hundreds
Z has size N x 1
Mu has size K x D

I'm hoping to get input on what exactly the "best practice" is to allocate the new memory for Z,Mu so that it will play nice with Matlab. So far, I'm using Matlab's provided mex utilities to do the allocating, and then using Eigen's Map interface so the matrices are accessible to Eigen. Here's my skeleton of code for the relevant mex function:

Code: Select all
typedef Map<ArrayXXd,Aligned> MexMat;  // Matlab is aligned and column-major ordered.

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{   
   int N = mxGetM( prhs[0] ); // # rows of X
   int D = mxGetN( prhs[0] ); // # cols of X
   MexMat X ( mxGetPr(prhs[0]), N, D); // map X
   
   // Create output matrices!
   plhs[0] = mxCreateDoubleMatrix(K, D, mxREAL);
   MexMat Mu ( mxGetPr(plhs[0]), K, D );
 
   plhs[1] = mxCreateDoubleMatrix(N, 1, mxREAL);
   MexMat Z  ( mxGetPr(plhs[1]), N, 1 );

   // My custom function using eigen to compute Z, Mu using X
   doWork( X, Z, Mu );
}


The code above runs fine. But I'm just curious if I should be using the matlab allocation function (mxCreateDoubleMatrix) or if it would be better to use Eigen's allocation and then somehow get Matlab to read that in without copying all the data. Thoughts?

Also, in what cases is it best to use the "aligned" in "Map<ArrayXXd,Aligned>" . I don't seem to see a speed-up either way. Would I be better off specifying a stride as well?

Thanks!
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Using MatLab's allocator should be fine. For large matrices, the 'Aligned' flag does not help much because actual alignement is determined at runtime.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Sogou [Bot], Yahoo [Bot]