用户定义的结构,带有MATLAB mex函数

时间:2012-01-15 20:53:13

标签: c matlab struct mex

我试图通过使用mex函数将我的C代码链接到MATLAB,我担心我很困惑。具体来说,我想知道我是否可以使用自己的用户定义数据类型(例如下面示例中的Person结构)。我没有在文档中看到任何建议我可以,但如果不允许这样做会很不幸!这就是我对网关功能的看法:

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])  
{   

 int *inA;   
 int *inB;   
 const mxArray *people;   
 const char *fieldnames[5];  
 int numFields, i;  

 inA = (int *) mxGetPr(prhs[0]);  
 inB = (int *) mxGetPr(prhs[1]);  

 numFields = 5;  
 fieldnames[0] = "home";  
 fieldnames[1] = "work";  
 fieldnames[2] = "mode";  
 fieldnames[3] = "loc1";  
 fieldnames[4] = "loc2";  

 people = mxCreateStructMatrix(1000, 1, numFields, fieldnames);  
 for (i = 0; i < numFields; i++)  
 {  
    mxSetField(people,i,fieldnames[i],mxDuplicateArray(prhs[2]));  
 }  

 makePeople(inA, inB, people);  

}

我的makePeople函数定义如下:

void makePeople(int* A, int* B, Person* people)  
{  

 int MANHATTAN, BRONX, BROOKLYN, QUEENS, STATEN;  

 int i, j, k, p, q, n;  
 int count, home, work, mode;  
 double* loc1;  
 double* loc2;  
 Person oPerson;  

 n = 5;  
 count = 0;  

 MANHATTAN = 1;  
 BRONX = 2;  
 BROOKLYN = 3;  
 QUEENS = 4;  
 STATEN = 5;  

 for (i = 1; i <= n; i++)  
 {  
     for (j = 1; j <= n; j++)  
     {  
          for (k = 1; k <= 2; k++)  
          {  
               if (k == 1)  
                    q = A[n*i+j];  
               else  
                    q = B[n*i+j];  
               for (p = 1; p < q; p++)  
               {  
                    home = i;  
                    work = j;  
                    mode = k;  
                    if (home == MANHATTAN)  
                    {
                          loc1[0] = 2.4;  
                          loc1[1] = 2.4;  
                          loc2[0] = 3.7;  
                          loc2[1] = 3.4;  
                    }  
                    else
                    {  
                          loc1[0] = 3.4;  
                          loc1[1] = 4.4;
                          loc2[0] = 3.7;  
                          loc2[1] = 3.4;  
                    }
                    oPerson = Person_new(home, work, mode, loc1, loc2);  
                    people[count] = oPerson;  
                    count++;  
                    }  
              }  
        }  
  }  
  return;  

}

最后,这是person.h文件:

 #ifndef PERSON_INCLUDED  
 #define PERSON_INCLUDED  

 typedef struct Person_str *Person;  

 Person Person_new(int home, int work, int mode, double* loc1, double* loc2);  

 #endif  

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:6)

在MEX中,MATLAB结构的类型为mxArray,与您的自定义C结构Person完全不同。因此你不能只分配:

people[count] = oPerson;

// people is defined as: mxArray*
// oPerson is defined as: Person

您必须逐个填写MATLAB结构,就像在代码开头一样,通过mxSetField

填写