https://victorfang.wordpress.com/2011/09/06/

 

아래의 코드에서

원래는 cc[i*n + j] = aa[i*n + j] + bb[i*n + j];가 comment돼 있으나, 이걸 풀고
//C[i*n + j] = A[i*n + j] + B[i*n + j]; 이것을 comment시켜야 mex가 된다.

 

To access the variables, you need to associate a pointer to the data in the mxArray. Once you do this, accessing the variables is very simple.


a = mxGetPr(a_in_m);
b = mxGetPr(b_in_m);
c = mxGetPr(c_out_m);
d = mxGetPr(d_out_m);

Now it is possible to access the arrays with standard C or C++ [] notation. There are three important things to remember though:

  • You use 0-based indexing as always in C
  • You still use column-first indexing like in Matlab, though
  • To access the arrays, you use linear indexing (you can’t use [x][y], you have to use [y+x*dimy]

With those three things in mind, go crazy. You can use standard C libraries (as long as you include them). You can use for loops as much as your heart desires, and your code will be much, much faster than its Matlab equivalent.

 

 

Note that if we access using C[x] , we will get this error. In other words, we need to define another pointer to access the input memory space using: double *cc = mxGetPr(C);

 

>> mex mextest.cpp
mextest.cpp
mextest.cpp(36) : error C2036: ‘mxArray *’ : unknown size
mextest.cpp(36) : error C2036: ‘const mxArray *’ : unknown size
mextest.cpp(36) : error C2036: ‘const mxArray *’ : unknown size
mextest.cpp(36) : error C2676: binary ‘+’ : ‘const mxArray’ does not define this operator or a conversion to a type acceptable to the predefined operator

C:\PROGRA~2\MATLAB\R2010B\BIN\MEX.PL: Error: Compile of ‘mextest.cpp’ failed.

??? Error using ==> mex at 208
Unable to complete successfully.

 

 

 

My working code:

#include “mex.h”

void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* more C/C++ code … */
/* Check for proper number of arguments */
if (nrhs != 2) {
mexErrMsgTxt(“Two input arguments required.”);
} else if (nlhs > 1) {
mexErrMsgTxt(“Too many output arguments.”);
}

const mxArray *A = prhs[0];
const mxArray *B = prhs[1];

/* Check the dimensions of Y.  Y can be 4 X 1 or 1 X 4. */
int m = mxGetM(A);
int n = mxGetN(A);

if (!mxIsDouble(A) || mxIsComplex(A) ) {
mexErrMsgTxt(“YPRIME requires that Y be a 4 x 1 vector.”);
}

/* Create a matrix for the return argument */
mxArray *C;
C = plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);

double *cc = mxGetPr(C);
double *aa = mxGetPr(A);
double *bb = mxGetPr(B);

for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
//cc[i*n + j] = aa[i*n + j] + bb[i*n + j];
C[i*n + j] = A[i*n + j] + B[i*n + j];
}
}

}

Posted by uniqueone
,