C++ MATLAB中MEX函数的逻辑输出问题
为什么我的MEX函数的输出总是1,尽管它应该是0 我编写了以下MEX源代码,如下所示C++ MATLAB中MEX函数的逻辑输出问题,c++,matlab,mex,C++,Matlab,Mex,为什么我的MEX函数的输出总是1,尽管它应该是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); /*
#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
我想给你指一下我的文件。文件的一部分说: 返回 指向
mxArray
中第一个逻辑元素的指针。如果mxArray
不是逻辑数组,则结果为未指定
您传递的是一个双精度
数字,不是逻辑
。通过这样做,您将获得未定义的行为。因此,有三种方法可以解决此错误:
逻辑值传递给函数
true
和false
,而不是*y=1
和*y=0
,但输入必须是双精度
logical/bool
的任何引用更改为double
。具体来说,将mxGetLogicals
更改为,以便可以获得指向双精度实数数组的指针。您还需要将mxCreateLogicalMatrix
更改为,并且必须将指针从bool
更改为double
逻辑值传递给函数:
您只需执行以下操作:
y = test(false);
或:
通过这些更改运行此命令,可以获得以下信息:
>> y = test(false)
y =
1
>> y = test(true)
y =
0
选项2-输入类型为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
>> y = test(0)
y =
1
>> y = test(5)
y =
0
选项3-将bool
行为更改为double
:
使用上述更改运行此代码会使我:
>> y = test(0)
y =
1
>> y = test(5)
y =
0
>> y = test(0)
y =
1
>> y = test(5)
y =
0
是否也可以将函数更改为接受双输入但仍输出逻辑?@aschepler是的。我只是没想到。我将在中添加另一个选项。我的答案有帮助吗?是的,非常感谢:)