User`s manual

2 Creating C Language MEX-Files
2-16
/* Create a pointer to the input matrix y. */
y = mxGetPr(prhs[1]);
/* Get the dimensions of the matrix input y. */
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
/* Set the output pointer to the output matrix. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Create a C pointer to a copy of the output matrix. */
z = mxGetPr(plhs[0]);
/* Call the C subroutine. */
xtimesy(x,y,z,mrows,ncols);
}
As this example shows, creating MEX-file gateways that handle multiple
inputs and outputs is straightforward. All you need to do is keep track of which
indices of the vectors
prhs and plhs correspond to the input and output
arguments of your function. In the example above, the input variable
x
corresponds to
prhs[0] and the input variable y to prhs[1].
Note that
mxGetScalar returns the value of x rather than a pointer to x. This
is just an alternative way of handling scalars. You could treat
x as a 1-by-1
matrix and use
mxGetPr to return a pointer to x.
Passing Structures and Cell Arrays
Structures and cell arrays were new data types introduced in MATLAB 5. For
a discussion of the features of structures and cell arrays and the built-in
functions MATLAB provides for manipulating them, refer to “Structures and
Cell Arrays” in the Using MATLAB manual. Like all other data types in
MATLAB, structures and cell arrays can be passed into and out of C MEX-files.
Passing structures and cell arrays into MEX-files is just like passing any other
data types, except the data itself is of type
mxArray. In practice, this means that
mxGetField (for structures) and mxGetCell (for cell arrays) return pointers of
type
mxArray. You can then treat the pointers like any other pointers of type
mxArray, but if you want to pass the data contained in the mxArray to a C
routine, you must use an API function such as
mxGetData to access it.