我想向您指出mxGetLogicals 的文档。部分文档说:
返回
指向mxArray 中第一个逻辑元素的指针。如果mxArray 不是逻辑数组,则结果为未指定。
您传递的是 double 精度数字,不是 logical。通过这样做,您将获得未定义的行为。因此,您可以通过三种方式解决此错误:
- 将实际的
logical 值传递给函数。
- 保留所有内容,但更改您返回的内容。而不是
*y = 1 和*y = 0,将其分别更改为true 和false,但输入必须是double。
- 您基本上必须将任何对
logical / bool 的引用更改为double。具体来说,将mxGetLogicals 更改为mxGetPr,这样您就可以获得指向double 精度实数数组的指针。您还需要将mxCreateLogicalMatrix 更改为mxCreateDoubleMatrix,并且您必须将您的指针从bool 更改为double。
选项 #1 - 将 logical 值传递给函数:
您只需要这样做:
y = test(false);
或:
y = test(true);
使用这些更改运行它会给我以下信息:
>> 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
选项 #3 - 将 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