代码之家  ›  专栏  ›  技术社区  ›  zlon

如何只复制数组的一部分以输出到mex文件中?

  •  1
  • zlon  · 技术社区  · 6 年前

    我有以下MEX文件的示例:

    #include "mex.h"
    #include <random>
    
    void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
    {
     int nIterations = 10;
     double *Out,K[nIterations];
     mxArray *mxOut;
    
     std::random_device rnd_device;
     std::mt19937_64 rg(rnd_device());
     std::normal_distribution<double> Xi(0,1);
    
     int nStep = 0;
    
     for (int i=0; i<nIterations;i++){
        K[i] = Xi(rg);
        nStep++;
        if (K[i]>0.2){break;}
     }
     plhs[0] = mxCreateNumericMatrix(nStep,1, mxDOUBLE_CLASS, mxREAL);
     Out  = (double*) mxGetData(plhs[0]);
    
     // I want to avoid this cycle
     for (int i=0; i<nStep;i++){
        Out[i] = K[i];
    
     }
    }
    

    主要的想法是我知道输出的最大大小(在本例中是10),但是从运行到运行 K 可能不同(从1到10)。因此,我在片段的末尾执行一个复制循环。 在我的示例中,是否可以避免最后一个循环?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Brice    6 年前

    好吧,你可以 #include <string.h> 并将循环替换为普通和基本的内存副本: memcpy(Out,K,nStep * sizeof(*K));


    另一个可能更糟糕的解决方案是分配足够的内存来存储所有迭代 Out ,然后用重新分配内存 mxRealloc 以便matlab能够正确地跟踪内存分配。

    plhs[0] = mxCreateNumericMatrix(nIterations,1, mxDOUBLE_CLASS, mxREAL);
    Out  = (double*) mxGetData(plhs[0]);
    
    // draw up to nIterations numbers 
    for (int i=0; i<nIterations;i++){
       Out[i] = Xi(rg);
       nStep++;
       if (Out[i]>0.2){break;}
    }
    
    // reallocate memory and set nb of rows
    mxSetData(plhs[0],mxRealloc(Out,nStep * sizeof(*Out)));
    mxSetM(plhs[0],nStep);
    
        2
  •  1
  •   Muhammad Moustafa    6 年前

    我想在C里没有办法。

    另一个解决方法是将数组和nstep变量发送到matlab并在那里处理数组切片。