Lets use my example from above (if you forgot: [z0,z1] = jasonsFunction(x,y,z);).
Assume that x is a 2-D matrix, y is a string, and z is an integer. Here we wills ee how to extract
and use these different types of data.
We have access to the input paramter x by a pointer held in the array prhs. In C, when referencing
an array by index, the variable is automatically dereferenced (ie: you dont need to use a star).
For clarity, I will copy the variable x over to an mxArray pointer named xData (This does not need
to be done for the code to work).
//---Inside mexFunction---
//Declarations
mxArray *xData;
double *xValues;
int i,j;
int rowLen, colLen;
double avg;
//Copy input pointer x
xData = prhs[0];
//Get matrix x
xValues = mxGetPr(xData);
rowLen = mxGetN(xData);
colLen = mxGetM(xData);
//Print the integer avg of each col to matlab console
for(i=0;i<rowLen;i++)
{
avg=0;
for(j=0;j<colLen;j++)
{
avg += xValues[(i*colLen)+j];
//Another Method:
//
//avg += *xValues++;
}
avg = avg/colLen;
printf("The average of row %d, is %d",i,(int)avg);
}
The function mxGetPr is used to get a pointer to the real data xData. This function takes a
pointer to an mxArray as the intput paramter, and returns a pointer array of doubles. A similar function
mxGetPi can be used for complex data. mxGetN and mxGetM return
integers of the lengths of the row and column in the matrix. If this were an array of data, one of these
return values would be zero. MATLAB gives the matrix as rows first, then columns (if you were to traverse
the matrix linearly) so to jump by position, (x,y) maps to x*colLen+y. MATLAB organizes
its arrays this way to reduce cache misses when the row traversal is on the outside loop. It is good to
code it this way if you are working for efficiency. printf()
will print out to the MATLAB command prompt.
Getting a string is very similar, but has its own method. The example below shows the procedure for getting
a string. Again, I will copy the input to a pointer called yData.
//---Inside mexFunction---
//Declarations
mxArray *yData;
int yLength;
char *TheString;
//Copy input pointer y
yData = prhs[1];
//Make "TheString" point to the string
yLength = mxGetN(yData)+1;
TheString = mxCalloc(yLength, sizeof(char)); //mxCalloc is similar to malloc in C
mxGetString(yData,TheString,yLength);
This last example shows how to get a simple integer. This is the method that has always worked
for me, but it seems kind of strange so I imagine there is another way to do this.
//---Inside mexFunction---
//Declarations
mxArray *zData;
int Num;
//Copy input pointer z
zData = prhs[2];
//Get the Integer
Num = (int)(mxGetScalar(zData));
//print it out on the screen
printf("Your favorite integer is: %d",Num);
Three data types have been shown here. There are several others and the MATLAB help as well
as the MATLAB example code shows how to use them. Now to export the data....
"Doug course at UIUC using the TI C54x DSP has been adopted by many EE, CE and CS depts Worldwide "