为什么这个 MEX 函数会产生意想不到的结果?

Why does this MEX function create unexpected results?

我正在学习Accelerating MATLAB Performance and on page 394这本书,这段代码是这样写的:

#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 hello.cpp 构建 MEX 代码后,应产生以下结果:

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

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

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

你有 3 个参数但只有两个 "%",所以它输出 "s() called with [name] inputs, [nrhs] output" 并且不使用 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);

感谢您提醒我 - 这是本书编辑阶段输入的错字 - 正确的代码是 printf('%s() called...(即开头的 % 被错误地删除了)。我会相应地更新勘误表。

希望本书的其余部分对您有所帮助。如果你这样做,那么请post a positive comment on Amazon