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

岁酱吖の 提交于 2019-11-27 07:46:36

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/5943953/how-to-return-a-float-value-from-a-mex-function-and-how-to-retrieve-it-from-m-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!