| MATLAB® | ![]() |
The MATLAB API provides a full set of routines that handle the various data types supported by MATLAB. For each data type there is a specific set of functions that you can use for data manipulation. The first example discusses the simple case of doubling a scalar. After that, the examples discuss how to pass in, manipulate, and pass back various data types, and how to handle multiple inputs and outputs. Finally, the sections discuss passing and manipulating various MATLAB types.
Source code for the examples in this section are located in the matlabroot/extern/examples/refbook directory. To build these examples, make sure you have a C compiler selected using the mex -setup command. Then at the MATLAB command prompt, type:
mex filename.c
where filename is the name of the example.
This section looks at source code for the examples. Unless otherwise specified, the term "MEX-file" refers to a source file.
Let's look at a simple example of C code and its MEX-file equivalent. Here is a C computational function that takes a scalar and doubles it:
#include <math.h>
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
return;
}To see the same function written in the MEX-file format (timestwo.c), open the file in the MATLAB Editor.
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, at the MATLAB prompt, type:
mex timestwo.c
This carries out the necessary steps to create the binary 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 =
4You 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 Microsoft Windows systems and mex.sh on UNIX[1] systems. In either case, typing:
mex filename
at the prompt produces a compiled version of your MEX-file.
In the above example, scalars are viewed as 1-by-1 matrices. Alternatively, you can use a special API function called mxGetScalar that returns the values of scalars instead of pointers to copies of scalar variables (timestwoalt.c). To see the alternative code (error checking has been omitted for brevity), open the file in MATLAB Editor.
This example passes the input scalar x by value into the timestwo_alt subroutine, but passes the output scalar y by reference.
Any MATLAB type can be passed to and from MEX-files. The example revord.c accepts a string and returns the characters in reverse order. To see the example, open the file in MATLAB Editor.
In this example, the API function mxCalloc replaces calloc, the standard C function for dynamic memory allocation. mxCalloc allocates dynamic memory using the MATLAB memory manager and initializes it to zero. You must use mxCalloc in any situation where C would require the use of calloc. The same is true for mxMalloc and mxRealloc; use mxMalloc in any situation where C would require the use of malloc and use mxRealloc where C would require realloc.
Note MATLAB automatically frees up memory allocated with the mx allocation routines (mxCalloc, mxMalloc, mxRealloc) upon exiting your MEX-file. If you don't want this to happen, use the API function mexMakeMemoryPersistent. |
The gateway routine mexFunction allocates memory for the input and output strings. Since these are C strings, they need to be one greater than the number of elements in the MATLAB string. Next the MATLAB string is copied to the input string. Both the input and output strings are passed to the computational subroutine (revord), which loads the output in reverse order. Note that the output buffer is a valid null-terminated C string because mxCalloc initializes the memory to 0. The API function mxCreateString then creates a MATLAB string from the C string, output_buf. Finally, plhs[0], the left-hand side return argument to MATLAB, is set to the MATLAB array you just created.
By isolating variables of type mxArray from the computational subroutine, you can avoid having to make significant changes to your original C code.
To build this example, at the command prompt type:
mex revord.c
Type:
x = 'hello world'; y = revord(x)
MATLAB displays:
The string to convert is 'hello world'. y = dlrow olleh
The plhs[] and prhs[] parameters are vectors that contain pointers to each left-hand side (output) variable and each right-hand side (input) variable, respectively. Accordingly, plhs[0] contains a pointer to the first left-hand side argument, plhs[1] contains a pointer to the second left-hand side argument, and so on. Likewise, prhs[0] contains a pointer to the first right-hand side argument, prhs[1] points to the second, and so on.
This example, xtimesy, multiplies an input scalar by an input scalar or matrix and outputs a matrix.
To build this example, at the command prompt type:
mex xtimesy.c
Using xtimesy with two scalars gives:
x = 7;
y = 7;
z = xtimesy(x,y)
z =
49Using xtimesy with a scalar and a matrix gives:
x = 9;
y = ones(3);
z = xtimesy(x,y)
z =
9 9 9
9 9 9
9 9 9To see the corresponding MEX-file C code xtimesy.c, open the file in the MATLAB Editor.
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 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.
This example takes an m-by-n structure matrix as input and returns a new 1-by-1 structure that contains these fields:
String input generates an m-by-n cell array
Numeric input (noncomplex, scalar values) generates an m-by-n vector of numbers with the same class ID as the input, for example, int, double, and so on.
To see the program phonebook.c, open the file in MATLAB Editor.
To build this example, at the command prompt type:
mex phonebook.c
To see how this program works, enter this structure:
friends(1).name = 'Jordan Robert'; friends(1).phone = 3386; friends(2).name = 'Mary Smith'; friends(2).phone = 3912; friends(3).name = 'Stacy Flora'; friends(3).phone = 3238; friends(4).name = 'Harry Alpert'; friends(4).phone = 3077;
The results of this input are:
phonebook(friends)
ans =
name: {1x4 cell }
phone: [3386 3912 3238 3077]Because MATLAB does not use stdin and stdout, C functions like scanf and printf cannot be used to prompt users for input. The following example shows how to use mexCallMATLAB with the input function to get a number from the user.
#include "mex.h"
#include "string.h"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
mxArray *new_number, *str;
double out;
str = mxCreateString("Enter extension: ");
mexCallMATLAB(1,&new_number,1,&str,"input");
out = mxGetScalar(new_number);
mexPrintf("You entered: %.0f ", out);
mxDestroyArray(new_number);
mxDestroyArray(str);
return;
}
Complex data from MATLAB is separated into real and imaginary parts. The MATLAB API provides two functions, mxGetPr and mxGetPi, that return pointers (of type double *) to the real and imaginary parts of your data.
This example, convec.c, takes two complex row vectors and convolves them. To see the example, open the file in MATLAB Editor.
To build this example, at the command prompt type:
mex convec.c
Entering these numbers at the MATLAB prompt:
x = [3.000 - 1.000i, 4.000 + 2.000i, 7.000 - 3.000i]; y = [8.000 - 6.000i, 12.000 + 16.000i, 40.000 - 42.000i];
and invoking the new MEX-file:
z = convec(x,y)
results in:
z = 1.0e+02 * Columns 1 through 4 0.1800 - 0.2600i 0.9600 + 0.2800i 1.3200 - 1.4400i 3.7600 - 0.1200i Column 5 1.5400 - 4.1400i
which agrees with the results that the built-in MATLAB function conv.m produces.
You can create and manipulate signed and unsigned 8-, 16-, and 32-bit data from within your MEX-files. The MATLAB API provides a set of functions that support these data types. The API function mxCreateNumericArray constructs an unpopulated N-dimensional numeric array with a specified data size. Refer to the entry for mxClassID in the online reference pages for a discussion of how the MATLAB API represents these data types.
Once you have created an unpopulated MATLAB array of a specified data type, you can access the data using mxGetData and mxGetImagData. These two functions return pointers to the real and imaginary data. You can perform arithmetic on data of 8-, 16- or 32-bit precision in MEX-files and return the result to MATLAB, which will recognize the correct data class.
The example, doubleelement.c, constructs a 2-by-2 matrix with unsigned 16-bit integers, doubles each element, and returns both matrices to MATLAB. To see the example, open the file in MATLAB Editor.
To build this example, at the command prompt type:
mex doubleelement.c
At the MATLAB prompt, entering:
doubleelement
produces:
ans =
2 6
4 8The output of this function is a 2-by-2 matrix populated with unsigned 16-bit integers.
You can manipulate multidimensional numerical arrays by using mxGetData and mxGetImagData to return pointers to the real and imaginary parts of the data stored in the original multidimensional array. The example, findnz.c, takes an N-dimensional array of doubles and returns the indices for the nonzero elements in the array. To see the example, open the file in the MATLAB Editor.
To build this example, at the command prompt type:
mex findnz.c
Entering a sample matrix at the MATLAB prompt gives:
matrix = [ 3 0 9 0; 0 8 2 4; 0 9 2 4; 3 0 9 3; 9 9 2 0]
matrix =
3 0 9 0
0 8 2 4
0 9 2 4
3 0 9 3
9 9 2 0This example determines the position of all nonzero elements in the matrix. Running the MEX-file on this matrix produces:
nz = findnz(matrix)
nz =
1 1
4 1
5 1
2 2
3 2
5 2
1 3
2 3
3 3
4 3
5 3
2 4
3 4
4 4The MATLAB API provides a set of functions that allow you to create and manipulate sparse arrays from within your MEX-files. These API routines access and manipulate ir and jc, two of the parameters associated with sparse arrays. For more information on how MATLAB stores sparse arrays, see The MATLAB Array.
The example, fulltosparse.c, illustrates how to populate a sparse matrix. To see the example, open the file in MATLAB Editor.
To build this example, at the command prompt type:
mex fulltosparse.c
At the MATLAB prompt, entering:
full = eye(5)
full =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1creates a full, 5-by-5 identity matrix. Using fulltosparse on the full matrix produces the corresponding sparse matrix.
spar = fulltosparse(full) spar = (1,1) 1 (2,2) 1 (3,3) 1 (4,4) 1 (5,5) 1
It is possible to call MATLAB functions, operators, M-files, and other binary MEX-files from within your C source code by using the API function mexCallMATLAB. The example, sincall.c, creates an mxArray, passes various pointers to a subfunction to acquire data, and calls mexCallMATLAB to calculate the sine function and plot the results. To see the example, open the file in MATLAB Editor.
To build this example, at the command prompt type:
mex sincall.c
Running this example:
sincall
displays the results:

Note It is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLAB. See the example below. |
The following example creates an M-file that returns two variables but only assigns one of them a value:
function [a,b] = foo[c] a = 2*c;
MATLAB displays the following warning message:
Warning: One or more output arguments not assigned during call to 'foo'.
If you then call foo using mexCallMATLAB, the unassigned output variable is now type mxUNKNOWN_CLASS.
This example, mexcpp.cpp, illustrates how to use C++ code with your C language MEX-file. It makes use of member functions, constructors, destructors, and the iostream include file. To see the example, open the file in the MATLAB Editor.
To build this example, at the command prompt type:
mex mexcpp.cpp
The calling syntax is mexcpp(num1, num2).
The routine defines a class, MyData, with member functions display and set_data, and variables v1 and v2. It constructs an object d of class MyData and displays the initialized values of v1 and v2. It then sets v1 and v2 to your input, num1 and num2, and displays the new values. Finally, cleanup of the object is done using the delete operator.
This example, mexatexit.cpp, illustrates C++ file handling features. To see the C++ code, open the C++ file in MATLAB Editor. To compare it with a C code example mexatexit.c, open the C file in the MATLAB Editor.
The C code example registers the mexAtExit function to perform cleanup tasks (close the data file) when the MEX-file clears. This example prints a message on the screen (using mexPrintf) when performing file operations fopen, fprintf, and fclose.
To build the mexatexit.c MEX-file, type:
mex mexatexit.c
If you type:
x = 'my input string'; mexatexit(x)
MATLAB displays:
Opening file matlab.data. Writing data to file.
To clear the MEX-file, type:
clear mexatexit
MATLAB displays:
Closing file matlab.data.
You can see the contents of matlab.data by typing:
type matlab.data
MATLAB displays:
my input string
The C++ example does not use the mexAtExit function. The file open and close functions are handled in a fileresource class. The destructor for this class (which closes the data file) is automatically called when the MEX-file clears. This example also prints a message on the screen when performing operations on the data file. However, in this case, the only C file operation performed is the write operation, fprintf.
To build the mexatexit.cpp MEX-file, make sure you have selected a C++ compiler, then type:
mex mexatexit.cpp
If you type:
z = 'for the C++ MEX-file'; mexatexit(x) mexatexit(z) clear mexatexit
MATLAB displays:
Writing data to file. Writing data to file.
To see the contents of matlab.data, type:
type matlab.data
MATLAB displays:
my input string for the C++ MEX-file
[1] UNIX is a registered trademark of The Open Group in the United States and other countries.
![]() | C Source MEX-Files | Advanced Topics | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |