【问题标题】:Array of int at the output of a mex filemex 文件输出处的​​ int 数组
【发布时间】:2012-03-15 05:58:33
【问题描述】:

我正在尝试创建一个 mex 函数,其条目是一个整数,其输出是一个整数数组。 所以函数看起来像:int *myFunction(unsigned int N)。 在 mexFunction 中,我声明了一个 int 类型的变量 *variab,然后

N = mxGetScalar(prhs[0]);

  /* assign a pointer to the output */
  siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
  plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
  vari = (int*) mxGetPr(plhs[0]); */
  /* Call the subroutine. */
  vari = myFunction(N);
  mexPrintf("The first value is %d\n", vari[0]);

问题是第一个值是正确的(其他的也经过检查并且也是正确的)但是当我调用例程 mxFunction(16) 时,我只得到 0 作为输出。 我想这是因为我的输出是一个 int 数组,但我不知道如何解决这个问题。有什么提示吗? 干杯。

【问题讨论】:

    标签: matlab int mex


    【解决方案1】:

    Matlab 默认处理双精度。您可以根据您的代码 sn-p 轻松地将它们转换为您的 mex 函数,如下例所示。我制作了一个执行演示算法的 myFunction。我没有返回数据类型,而是将其设为 void 函数并将指针传递给输出,以便它可以填充它。 . .

    /*************************************************************************/
    /* Header(s)                                                             */
    /*************************************************************************/
    #include "mex.h"
    #include "math.h"
    
    
    /*************************************************************************/
    /*the fabled myFunction                                                  */
    /*************************************************************************/
    void myFunction(unsigned int N, unsigned int siz, double* output)
    {
        int sign = 1;
        for(int ii=0; ii<siz; ++ii)
        {
            output[ii] = (double)(ii * sign + N);
            sign *= -1;
        }
    
    }
    
    
    /*************************************************************************/
    /* Gateway function and error checking                                   */
    /*************************************************************************/
    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
      /* variable declarations */
      unsigned int siz;
      double N;
    
      /*  check the number of input and output parameters  */  
        if(nrhs!=1)
            mexErrMsgTxt("One input arg expected");
        if(nlhs > 1)
            mexErrMsgTxt("Too many outputs");
    
      N = mxGetScalar(prhs[0]);
    
      /* assign a pointer to the output */  
      siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
      plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
      myFunction(N, siz, mxGetPr( plhs[0]) );
    }
    

    【讨论】:

    • +1 但是由于 OP 想要一个整数数组,他应该使用 mxCreateNumericArraymxCreateNumericMatrix 和适当的 mxClassID(例如 mxINT32_CLASS)来创建数组。然后使用mxGetData 获取指向数组开头的指针。
    • 公平点,但 OP 没有提供任何 Matlab 代码来伴随他们的问题,以使要求一目了然。最好谨慎行事,直到他们抱怨它不起作用:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多