2016-03-13 109 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

相關問題