Skip to content

Instantly share code, notes, and snippets.

@michaelchughes
Last active March 13, 2018 12:53
Show Gist options
  • Save michaelchughes/4742878 to your computer and use it in GitHub Desktop.
Save michaelchughes/4742878 to your computer and use it in GitHub Desktop.
Simple Mex function to take in two Matlab matrices and return their matrix product. R = MatrixProductMEX( X, Y); same as R = X*Y;
#include "Eigen/Dense"
#include "mex.h"
#include <iostream>
using namespace Eigen;
using namespace std;
typedef Map<MatrixXd> MexMat;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if ( nrhs != 2 ) {
mexErrMsgTxt("Needs 2 arguments -- X (NxD), Y (DxM)");
return;
}
int N = mxGetM( prhs[0] );
int D = mxGetN( prhs[0] );
int D2 = mxGetM( prhs[1] );
int M = mxGetN( prhs[1] );
if (D != D2 ) {
mexErrMsgTxt("X #cols needs to match Y #rows!");
return;
}
MexMat X ( mxGetPr(prhs[0]), N, D);
MexMat Y ( mxGetPr(prhs[1]), D, M);
// Create output matrix (using Matlab's alloc)
plhs[0] = mxCreateDoubleMatrix(N, M, mxREAL);
MexMat R ( mxGetPr(plhs[0]), N, M );
R = X * Y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment