2016-03-13 111 views
1

我学习的书Accelerating MATLAB Performancepage 394,这个代码写的是:为什么这个MEX函数会产生意想不到的结果?

#include "mex.h" 
void mexFunction (int nlhs,mxArray *plhs[],/*outputs*/ 
    int nrhs, const mxArray *prhs[])/*inputs*/ 
{ 
    const char *name = mexFunctionName(); 
    printf("s() called with %d inputs,%d outputs\n",name,nrhs,nlhs); 
} 

基于什么是在书中说,建设MEX代码的命令mex hello.cpp后,下面的结果应该产生:

>> hello 
hello() called with 0 inputs, 0 outputs 
>> hello(1,2,3) 
hello() called with 3 inputs, 0 outputs 
>> [a,b] = hello(1,2,3) 
hello() called with 3 inputs, 2 outputs 
One or more output arguments not assigned during call to "hello". 

但是,当我在我的Win7x64机器上运行相同的代码,结果如下:

>> mex hello.cpp 
Building with 'Microsoft Visual C++ 2010'. 
MEX completed successfully. 
>> hello 
s() called with 2082650752 inputs,0 outputs 
>> hello(1,2,3) 
s() called with 2082650752 inputs,3 outputs 
>> [a,b] = hello(1,2,3) 
s() called with 2082650752 inputs,3 outputs 
One or more output arguments not assigned during call to "hello". 

这些意外结果的原因是什么?

+1

上面的链接没有显示我的页面,但通过搜索页面可以访问:https://goo.gl/dGg5HA书中的代码示例是错误的。 – Daniel

+1

继[勘误](http://undocumentedmatlab.com/books/matlab-performance)之后,作者不知道,我给他发了一条消息。 – Daniel

回答

3

printf("s() called with %d inputs,%d outputs\n",name,nrhs,nlhs); 

你有3个参数,但只有两个 “%”,所以它输出 “()的调用与[NAME]输入,[nrhs]输出” 和nlhs不被使用。只是删除名称,改用

printf("s() called with %d inputs,%d outputs\n",nrhs,nlhs); 

或使用%s显示函数名称:

printf("%s called with %d inputs,%d outputs\n",name,nrhs,nlhs); 
4

谢谢你提醒我 - 这是这是在这本书的编辑阶段进入了一个错字 - 中正确的代码是printf('%s() called...(即,导致的%被误删)。我会相应地更新勘误表。

我希望你发现本书的其余部分有用。如果你这样做,那么请post a positive comment on Amazon

+0

这真是一本很棒的书。特别是第9章对我来说非常有用。 Coul你请看看我的代码[这里](http://goo.gl/wiscLt)并给我一些想法? – sepideh

相关问题