/* Did you include string.h? (for memcpy) */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
static double *A,*B;
mwSize dims[2] = {5,10}; // Use mwSize here, not int.
static double *U,*V;
mxArray *APPLE[1];
mxArray *Uin[2],*Uout[2];
if( nlhs < 2 ) {
mexErrMsgTxt("Not enough outputs.");
}
A = mxGetPr(mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL)); // MEMORY LEAK!
B = mxGetPr(mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL)); // MEMORY LEAK!
// In the above two lines, you lose the pointers to the mxArrays! Bad practice!
/* C code which fills A and B */
FILLAB(A,B);
Uin[0] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL);
Uin[1] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL);
memcpy(mxGetPr(Uin[0]),A,5*10*sizeof(double));
memcpy(mxGetPr(Uin[1]),B,5*10*sizeof(double));
Uout[0] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); // MEMORY LEAK!
Uout[1] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); // MEMORY LEAK!
// In the above two lines, the mxArrays created are lost by the subsequent
// call to mexCallMATLAB, which OVERWRITES the pointers in Uout[0] and Uout[1].
// This is not good programming practice! Just DELETE these two lines entirely!
mexCallMATLAB(2,Uout,2,Uin,"my_matlab_solver"); // This CREATES new outputs in Uout.
// Note, you could use plhs in the 2nd argument above and skipped the following
// two lines assigning Uout to plhs.
plhs[0] = Uout[0];
plhs[1] = Uout[1]; // Need nlhs >= 2 in order for this to work.
U = mxGetPr(plhs[0]);
V = mxGetPr(plhs[1]); // Need nlhs >= 2 in order for this to work.
APPLE[0] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL);
if( !mxIsDouble(plhs[1]) || mxIsSparse(plhs[1]) || mxGetNumberOfElements(plhs[1]) < 50 ) {
mexErrMsgTxt("plhs[1] is not full double class with 50 or more elements");
}
if( !mxIsDouble(plhs[0]) || mxIsSparse(plhs[0]) || mxGetNumberOfElements(plhs[0]) < 50 ) {
mexErrMsgTxt("plhs[0] is not full double class with 50 or more elements");
}
memcpy(mxGetPr(APPLE[0]),V,5*10*sizeof(double));
/*APPLE[0] = plhs[1]; */
mexCallMATLAB(0,NULL,1,&APPLE[0],"plot_variable");
// Note, you can just use APPLE in the 3rd argument above. No need to use &APPLE[0].
}
Best Answer