[英]Issue about logical output from MEX function in MATLAB
為什么輸出總是來自我的MEX功能,盡管它預計為0?
我寫了下面的MEX源代碼
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
bool *x,*y;
/* Create matrix for the return argument. */
plhs[0] = mxCreateLogicalMatrix(1,1);
/* Assign pointers to each input and output. */
x = mxGetLogicals(prhs[0]); //input
y = mxGetLogicals(plhs[0]); //output
/* Calculations. */
if (*x == 0) *y = 1;
else *y = 0;
}
並出現以下內容:
y = test(5)
y =
1
我想指出mxGetLogicals
的文檔。 部分文件說:
返回
指針在第一邏輯元件
mxArray
。 如果mxArray
不是邏輯數組,則結果未指定 。
你傳遞的是double
精度數, 而不是 logical
。 通過這樣做,您將獲得未定義的行為。 因此,有三種方法可以解決此錯誤:
logical
值傳遞給函數。 *y = 1
和*y = 0
,分別將其更改為true
和false
,但輸入必須為double
。 logical / bool
任何引用更改為double
。 具體來說,將mxGetLogicals
更改為mxGetPr
以便獲得指向double
精度實數組的指針。 您還需要將mxCreateLogicalMatrix
更改為mxCreateDoubleMatrix
並且必須將指針從bool
更改為double
。 logical
值傳遞給函數: 你只需要這樣做:
y = test(false);
要么:
y = test(true);
通過這些更改運行它會給我以下內容:
>> y = test(false)
y =
1
>> y = test(true)
y =
0
double
,輸出類型為bool
: 這些變化是您需要做的:
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
double *x;
bool *y; // Change
/* Create matrix for the return argument. */
plhs[0] = mxCreateLogicalMatrix(1,1);
/* Assign pointers to each input and output. */
x = mxGetPr(prhs[0]); //input - Change
y = mxGetLogicals(plhs[0]); //output
/* Calculations. */
if (*x == 0) *y = true; // Change
else *y = false;
}
使用上述更改運行此代碼可以讓我:
>> y = test(0)
y =
1
>> y = test(5)
y =
0
bool
行為改為double
: #include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
double *x,*y; // Change
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); // Change
/* Assign pointers to each input and output. */
x = mxGetPr(prhs[0]); //input - Change
y = mxGetPr(plhs[0]); //output - Change
/* Calculations. */
if (*x == 0) *y = 1;
else *y = 0;
}
使用上述更改運行此代碼可以讓我:
>> y = test(0)
y =
1
>> y = test(5)
y =
0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.