User`s manual
Examples of C MEX-Files
2-9
if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
!(mrows == 1 && ncols == 1) ) {
mexErrMsgTxt("Input must be a noncomplex scalar double.");
}
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Assign pointers to each input and output. */
x = mxGetPr(prhs[0]);
y = mxGetPr(plhs[0]);
/* Call the timestwo subroutine. */
timestwo(y,x);
}
In C, function argument checking is done at compile time. In MATLAB, you can
pass any number or type of arguments to your M-function, which is responsible
for argument checking. This is also true for MEX-files. Your program must
safely handle any number of input or output arguments of any supported type.
To compile and link this example source file at the MATLAB prompt, type
mex timestwo.c
This carries out the necessary steps to create the MEX-file called timestwo
with an extension corresponding to the platform on which you’re running. You
can now call
timestwo as if it were an M-function.
x = 2;
y = timestwo(x)
y =
4
You can create and compile MEX-files in MATLAB or at your operating
system’s prompt. MATLAB uses
mex.m, an M-file version of the mex script, and
your operating system uses
mex.bat on Windows and mex.sh on UNIX. In
either case, typing
mex filename
at the prompt produces a compiled version of your MEX-file.