Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a float value from a mex function, and how to retrieve it from m-file?

Tags:

matlab

mex

I understand that all the returned values of a mex function are stored in plhs array of type mxArray*. I want to return a value of type float. How can I do it?

Some code examples on returning it from the mex function and retrieving it from the m-file is much appreciated.

like image 291
drox Avatar asked May 10 '11 00:05

drox


1 Answers

The MATLAB class name for float type data is "single".

In the MEX-file you could write:

void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
    // Create a 2-by-3 real float
    plhs[0] = mxCreateNumericMatrix(2, 3, mxSINGLE_CLASS, mxREAL);

    // fill in plhs[0] to contain the same as single([1 2 3; 4 5 6]); 
    float * data = (float *) mxGetData(plhs[0]);
    data[0] = 1; data[1] = 4; data[2] = 2; 
    data[3] = 5; data[4] = 3; data[5] = 6;
}

Retrieving it from the M-file is pretty much like calling any other function. If you named the MEX-function foo, you'd call it like this:

>> x = foo;

Now x would contain the single-precision value equivalent to single([1 2 3; 4 5 6]) that was stored in plhs[0].

like image 74
SCFrench Avatar answered Nov 15 '22 10:11

SCFrench