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

前端 未结 1 1316
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 04:47

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

相关标签:
1条回答
  • 2020-12-11 05:22

    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].

    0 讨论(0)
提交回复
热议问题