Question about mxCallMATLAB in mex Files
3 views (last 30 days)
Show older comments
Hello Everyone. Suppose that I would like to call "randn" from within a mex file in order to take a draw from a normal distribution, and then subsequently manipulate that draw. I have tried doing this with the mxCallMATLAB function, but I have not succeeded in doing so. Here is some example code that would simply call randn from within the mex file and try to return the value as the output of the mex function (this is a contrived example, and what I really want to do is take draws form randn, and use them as part of a larger statistical function in the mex file).
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
double *Inputs;
double *outMatrix;
mxArray *Temp[1];
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
outMatrix = mxGetPr(plhs[0]);
mexCallMATLAB(1,Temp,0,NULL, "randn");
outMatrix[0]=Temp[0];
}
I am getting an error indicating that the "outMatrix[0]=Temp[0];" line is confusing data types. I suppose that I don't have a clear understanding of all of the issues at stake with the pointers for arrays of different data types. What should I do if I want to take the output from "randn" and store it in a double array (like outMatrix here), or otherwise operate on it like I would any other double array? Your help would be greatly appreciated!
0 Comments
Answers (2)
James Tursa
on 15 Apr 2013
Calling randn and returning a single value:
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mexCallMATLAB( 1, plhs, 0, NULL, "randn" );
}
Calling randn and returning a 1x5 vector of values:
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *arraysize;
double *pr;
arraysize = mxCreateDoubleMatrix(1,2,mxREAL);
pr = mxGetPr(arraysize);
pr[0] = 1;
pr[1] = 5;
mexCallMATLAB( 1, plhs, 1, &arraysize, "randn" );
mxDestroyArray(arraysize);
}
0 Comments
Jan
on 15 Apr 2013
outMatrix is a pointer to the data which are contained in an mxArray, while Temp is a pointer to the mxArray itself.
You need to use another pointer to a double array mxGetPr(Temp) to access the data of the created mxArray object.
0 Comments
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!