【问题标题】:Issue about logical output from MEX function in MATLAB关于 MATLAB 中 MEX 函数的逻辑输出的问题
【发布时间】:2015-12-18 13:15:24
【问题描述】:

为什么我的 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);

  /* 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

【问题讨论】:

  • 我的回答有帮助吗?
  • 是的,非常感谢:)

标签: c++ matlab mex


【解决方案1】:

我想向您指出mxGetLogicals 的文档。部分文档说:

返回

指向mxArray 中第一个逻辑元素的指针。如果mxArray 不是逻辑数组,则结果为未指定

您传递的是 double 精度数字,不是 logical。通过这样做,您将获得未定义的行为。因此,您可以通过三种方式解决此错误:

  1. 将实际的logical 值传递给函数。
  2. 保留所有内容,但更改您返回的内容。而不是*y = 1*y = 0,将其分别更改为truefalse,但输入必须是double
  3. 您基本上必须将任何对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

【讨论】:

  • 是不是也可以把函数改成接受双输入但仍输出逻辑?
  • @aschepler 是的。我只是没想到。我将添加其他选项。
猜你喜欢
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多