如何从mex函数返回浮点值,以及如何从m文件中检索它? [英] How to return a float value from a mex function, and how to retrieve it from m-file?
问题描述
我知道mex函数的所有返回值都存储在mxArray *类型的plhs数组中.我想返回一个float类型的值.我该怎么办?
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?
从mex函数返回它并从m文件中检索它的一些代码示例受到人们的赞赏.
Some code examples on returning it from the mex function and retrieving it from the m-file is much appreciated.
推荐答案
浮点类型数据的MATLAB类名称为单个".
The MATLAB class name for float type data is "single".
在MEX文件中,您可以编写:
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;
}
从M文件中检索它非常类似于调用任何其他函数.如果您将MEX函数命名为foo
,则将其命名为:
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;
现在x
将包含与single([1 2 3; 4 5 6])
等效的单精度值,该值存储在plhs[0]
中.
Now x
would contain the single-precision value equivalent to single([1 2 3; 4 5 6])
that was stored in plhs[0]
.
这篇关于如何从mex函数返回浮点值,以及如何从m文件中检索它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!