matovitch
matovitch

Reputation: 1284

How to set the classID of an mxArray filled with mxSetData?

I am trying to use mex.h header to convert a c++ program I wrote into a Matlab command and I don't get how their mxArray struct works.

Let say I have a std::vector<float> called data that I want to convert to an mxArray I can return back to matlab, I will have to do something like this right ?

mxSetData(plhs[0], static_cast<void*>(&(*(data.begin()))));
mxSetN(plhs[0], data.size());
mxSetM(plhs[0], 1);

But then how do matlab know the mxClassID of the mxArray I want to send is mxSINGLE_CLASS ? Why shouldn't I use mxSetData for double data ? And why doesn't mxSetClassID exists ?

Upvotes: 1

Views: 279

Answers (1)

Shai
Shai

Reputation: 114786

It seems like you need to pre-dfine plhs[0] as float type and then set the pointer.

plhs[0] = mxCreateNumericMatrix( 1, data.size(), mxSINGLE_CLASS, mxREAL );
void* oldAllocation = mxGetData( plhs[0] ); // for de-allocation
mxSetData(plhs[0], static_cast<void*>(&(*(data.begin()))));
mxFree( oldAllocation );

BTW, are you sure data is on the heap and won't be de-allocated when your mex function terminates?


Alternatively, if data is not too big, you can simply copy it into plhs[0] (this is what I usually do)

plhs[0] = mxCreateNumericMatrix( 1, data.size(), mxSINGLE_CLASS, mxREAL );
float* dst = (float*)mxGetData( plhs[0] ); 
for ( int i = 0 ; i < data.size(); i++ ) {
    dst[i] = data[i];
}
// or use memcpy instead of the loop

Upvotes: 1

Related Questions