首页 文章

从mex中的matlab结构中提取数据

提问于
浏览
0

我跟着this example但是我不确定我错过了什么 . 具体来说,我在MATLAB中有这个结构:

a = struct; a.one = 1.0; a.two = 2.0; a.three = 3.0; a.four = 4.0;

这是我在MEX中的测试代码---

首先,我想确保我传递的是正确的东西,所以我做了这个检查:

int nfields = mxGetNumberOfFields(prhs[0]);
mexPrintf("nfields =%i \n\n", nfields);

它确实产生 4 ,因为我有四个字段 .

但是,当我尝试在 three 字段中提取值时:

tmp = mxGetField(prhs[0], 0, "three");
mexPrintf("data =%f \n\n",  (double *)mxGetData(tmp)  );

它返回 data =1.000000 . 我不确定我做错了什么 . 我的逻辑是我想获得字段 three 的第一个元素(因此索引是0),所以我期望 data =3.00000 .

我可以获得指针或提示吗?

1 回答

  • 1

    EDITED

    好的,既然你没有提供完整的代码,但是你正在进行测试,那么让我们尝试从头开始创建一个新代码 .

    在Matlab端,使用以下代码:

    a.one = 1;
    a.two = 2;
    a.three = 3;
    a.four = 4;
    
    read_struct(a);
    

    现在,创建并编译MEX read_struct 函数,如下所示:

    #include "mex.h"
    
    void read_struct(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
        if (nrhs != 1)
            mexErrMsgTxt("One input argument required.");
    
        /* Let's check if the input is a struct... */
        if (!mxIsStruct(prhs[0]))
            mexErrMsgTxt("The input must be a structure.");
    
        int ne = mxGetNumberOfElements(prhs[0]);
        int nf = mxGetNumberOfFields(prhs[0]);
    
        mexPrintf("The structure contains %i elements and %i fields.\n", ne, nf);
    
        mwIndex i;
        mwIndex j;
    
        mxArray *mxValue; 
        double *value;
    
        for (i = 0; i < nf; ++i)
        {
            for (j = 0; j < ne; ++j)
            {
                mxValue = mxGetFieldByNumber(prhs[0], j, i);
                value = mxGetPr(mxValue);
    
                mexPrintf("Field %s(%d) = %.1f\n", mxGetFieldNameByNumber(prhs[0],i), j, value[0]);
            }
        }
    
        return;
    }
    

    这是否正确打印您的结构?

相关问题