Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...