簡體   English   中英

關於MATLAB中MEX函數的邏輯輸出問題

[英]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 通過這樣做,您將獲得未定義的行為。 因此,有三種方法可以解決此錯誤:

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM