Mex, how to copy an array to output

4 views (last 30 days)
In my mex function my_expm.c, I calculated matrix expoential for the input matrix,
void mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[])
double *inputMat;
double *outputMat;
int numRows;
inputMat = mxGetDoubles(prhs[0]);
numRows = mxGetM(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(numRows, numRows, mxREAL);
outputMat = mxGetDoubles(plhs[0]);
outputMat = r8mat_expm1(numRows, inputMat); // matrix exponential
Calling it by
c = my_expm([1,0;0,1])
will return all zeros, as explained in this post.
I tried the two suggestions in that post to fix this problem, both failed.
by using
r8mat_expm1(numRows, inputMat, outputMat)
instead of
outputMat = r8mat_expm1(numRows, inputMat);
this still returns all zeros. I used gdb to debug, it turns out when using outputMat = r8mat_expm1(numRows, inputMat),the outputMat in mex is right and when it returns to matlab, they all become zero. But when using r8mat_expm1(numRows, inputMat, outputMat), the outputMat in mex are already all zeros. I do not know why they are zeros since I only simply changed the signature of r8mat_expm1().
by using mxSetDoubles(), as in this post. This call get the work done. However, this mex function can run only once, if I call it again, matlab will crash. I can not see whether there is a problem with mxSetDoubles().
So, is there another way that I can simply copy outputMat to plhs[0]?

Accepted Answer

James Tursa
James Tursa on 26 Dec 2020

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!