/ Published in: C++
This code is a demonstration of writing mex functions using the armadillo scientific library. Please see my blog post for more details and leave comments there.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include "mex.h" #include "math.h" #include<armadillo> using namespace arma; void importMatlab(mat& A, const mxArray *mxdata){ access::rw(A.mem)=mxGetPr(mxdata); access::rw(A.n_rows)=mxGetM(mxdata); access::rw(A.n_cols)=mxGetN(mxdata); access::rw(A.n_elem)=A.n_rows*A.n_cols; }; void freeVar(mat& A, const double *ptr){ access::rw(A.mem)=ptr; access::rw(A.n_rows)=1; access::rw(A.n_cols)=1; access::rw(A.n_elem)=1; }; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 3) mexErrMsgTxt("Incorrect number of input arguments"); if (nlhs != 1) mexErrMsgTxt("Incorrect number of D arguments"); mat X(1,1); const double* Xmem=access::rw(X.mem); importMatlab(X,prhs[0]); mat Y(1,1); const double* Ymem=access::rw(Y.mem); importMatlab(Y,prhs[1]); mat W(1,1); const double* Wmem=access::rw(W.mem); importMatlab(W,prhs[2]); // check if the input corresponds to what you are expecting if(( X.n_cols != Y.n_cols ) || (Y.n_cols != W.n_cols ) ) mexErrMsgTxt("Columns of X, Y, and W must be of equal length!"); if( W.n_rows != W.n_cols ) mexErrMsgTxt("W must be a square matrix!"); plhs[0] = mxCreateDoubleMatrix(X.n_rows, Y.n_rows, mxREAL); double *out = mxGetPr(plhs[0]); mat diff; mat M; int k=0; for(int y=0;y<Y.n_rows;y++) for(int x=0;x<X.n_rows;x++){ // (X(x,:)-Y(y,:))*W*((X(x,:)-Y(y,:))') diff=X.row(x)-Y.row(y); M=diff*W*trans(diff); (*out++)=M(0); } freeVar(X,Xmem); freeVar(Y,Ymem); freeVar(W,Wmem); return; }
URL: http://www.myoutsourcedbrain.com/2009/08/mex-function-for-mahalanobis-function.html