converting to/from C++ arrays to mxArrays

5 views (last 30 days)
Peter
Peter on 9 May 2011
Hi everyone, I'm trying to write some code in c++ to speed up a computationally difficult portion of my matlab code. Could anyone lend some pointers on the best way to convert from mxArray/vector to C++ and back?
I've looked at the examples, but unfortunately they seem to keep everything in their own variable type.
here's what ive been trying (input is a structure with the first element the vector I'm interested in exporting)
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *tmp;
double *pdata=NULL;
tmp = mxGetFieldByNumber(prhs[0],0,0);
pdata = mxGetPr(tmp);
// This part tries to convert to the N_Vector format I need for the sundials solver I use in the C++ routine. UserData is just a structure / class. Needs the number of values, NP (constant) and a pointer to the first value (in type double (realtype))
UserData *data = new UserData;
data->param = N_VMake_Serial(NP,static_cast<realtype*>(pdata));
I'm not able to have the parameter set get passed to the rest of the routine. If i output pdata, pdata[0], or *pdata, I get pointers for all of them. Where are the values? If I could even convert them to a regular c++ array I would know how to process them from there.

Answers (1)

James Tursa
James Tursa on 9 May 2011
pdata is a regular C++ pointer and can be used as a regular C++ array in most contexts. Try checking the API results to see that you are getting what you expect before using them. e.g.,
if( !mxIsStruct(prhs[0] ) {
// error, not a struct, take action
}
if( mxIsEmpty(prhs[0]) ) {
// error, empty, take action
}
tmp = mxGetFieldByNumber(prhs[0],0,0);
if( !tmp ) {
// error, field is NULL, take action
}
if( !mxIsDouble(tmp) ) {
// error, not a double, take action
}
if( mxIsEmpty(tmp) ) {
// error, empty, take action
}
NP = mxGetNumberOfELements(tmp);
pdata = mxGetPr(tmp);
Q: Why are you doing a static cast on pdata? Can't you just pass pdata directly since it is a double * and N_VMake_Serial is expecting a double * by default? I would think that using a static cast here would be a mistake (i.e., masking an actual coding error if pdata type did not match realtype)
  3 Comments
James Tursa
James Tursa on 9 May 2011
%d is a decimal int format. Use %f or %g instead.
Peter
Peter on 9 May 2011
:)
thanks so much for your help!! Never used the printf command before having to use the matlab API, always used cout <<.

Sign in to comment.

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!