| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Because the MATLAB interpreter chooses the binary MEX-file when both an M-file and a MEX-file with the same name are encountered in the same folder, it is possible to use M-files for documenting the behavior of your binary MEX-files. The help command automatically finds and displays the appropriate M-file when help is requested and the interpreter finds and executes the corresponding binary MEX-file when the function is invoked.
You can combine multiple source files, object files, and file libraries to build a binary MEX-file. To do this, list the additional files, with their file extensions, separated by spaces. The name of the resulting MEX-file is the name of the first file in the list.
The following command combines multiple files of different types into a binary MEX-file called circle.ext, where ext is the extension corresponding to the current platform:
mex circle.F square.o rectangle.F shapes.o
You may find it useful to use a software development tool like MAKE to manage MEX-file projects involving multiple source files. Simply create a MAKEFILE that contains a rule for producing object files from each of your source files, and then invoke the mex build script to combine your object files into a binary MEX-file. This way you can ensure that your source files are recompiled only when necessary.
Note On Linux[1] systems, you must use the -fortran switch to the mex script if you are linking Fortran objects. |
Unlike M-file functions, MEX-file functions (binary MEX-files) do not have their own variable workspace. MEX-file functions operate in the caller's workspace. mexEvalString evaluates the string in the caller's workspace. In addition, you can use the mexGetVariable and mexPutVariable routines to get and put variables into the caller's workspace.
Binary MEX-files built on 64-bit platforms can handle 64-bit mxArrays. These large data arrays can have up to 248–1 elements. The maximum number of elements a sparse mxArray can have is 248-2.
Using the following instructions creates platform-independent binary MEX-files as well.
Your system configuration can impact the performance of MATLAB. The 64-bit processor requirement enables you to create the mxArray and access data in it. However, your system's memory, in particular the size of RAM and virtual memory, determine the speed at which MATLAB processes the mxArray. The more memory available, the faster the processing.
The amount of RAM also limits the amount of data you can process at one time in MATLAB. For guidance on memory issues, see Strategies for Efficient Use of Memory in the Programming Fundamentals documentation. Memory management within source MEX-files can have special considerations, as described in Memory Management.
To work with a 64-bit mxArray, your source code must comply with the 64-bit API, which consists of the functions in the following table.
| mxCalcSingleSubscript | mxCreateSparseLogicalMatrix |
| mxCalloc | mxCreateStructArray |
| mxCopyCharacterToPtr | mxCreateStructMatrix |
| mxCopyComplex16ToPtr | mxGetCell |
| mxCopyComplex8ToPtr | mxGetDimensions |
| mxCopyInteger1ToPtr | mxGetElementSize |
| mxCopyInteger2ToPtr | mxGetField |
| mxCopyInteger4ToPtr | mxGetFieldByNumber |
| mxCopyPtrToCharacter | mxGetIr |
| mxCopyPtrToComplex16 | mxGetJc |
| mxCopyPtrToComplex8 | mxGetM |
| mxCopyPtrToInteger1 | mxGetN |
| mxCopyPtrToInteger2 | mxGetNumberOfDimensions |
| mxCopyPtrToInteger4 | mxGetNumberOfElements |
| mxCopyPtrToPtrArray | mxGetNzmax |
| mxCopyPtrToReal4 | mxGetProperty |
| mxCopyPtrToReal8 | mxGetString |
| mxCopyReal4ToPtr | mxMalloc |
| mxCopyReal8ToPtr | mxRealloc |
| mxCreateCellArray | mxSetCell |
| mxCreateCellMatrix | mxSetDimensions |
| mxCreateCharArray | mxSetField |
| mxCreateCharMatrixFromStrings | mxSetFieldByNumber |
| mxCreateDoubleMatrix | mxSetIr |
| mxCreateLogicalArray | mxSetJc |
| mxCreateLogicalMatrix | mxSetM |
| mxCreateNumericArray | mxSetN |
| mxCreateNumericMatrix | mxSetNzmax |
| mxCreateSparse | mxSetProperty |
Functions in this API use the mwIndex, mwSize, and mwPointer preprocessor macros. For information about using these macros, see Required Header Files.
Use the mex build script option -largeArrayDims with the 64-bit API.
When using the 64-bit API, mwSize and mwIndex are equivalent to size_t in C or INTEGER*8 in Fortran. These types are unsigned, unlike int and INTEGER*4, which are the types used in the 32-bit API. Be careful not to pass any negative values to functions that take mwSize or mwIndex arguments. Do not cast negative int or INTEGER*4 values to mwSize or mwIndex; the returned value cannot be predicted. Instead, change your code to avoid using negative values.
If you develop cross-platform applications (programs that can run on both 32- and 64-bit architectures), you must pay attention to the upper limit of values you use for mwSize and mwIndex. The 32-bit application reads these values and assigns them to variables declared as int in C or INTEGER*4 in Fortran. Be careful to avoid assigning a large mwSize or mwIndex value to an int, INTEGER*4, or other variable that might be too small.
When a binary MEX-file returns control to MATLAB, it returns the results of its computations in the output arguments—the mxArrays contained in the left-hand side arguments plhs[]. MATLAB destroys any mxArray created by the MEX-file that is not in this argument list. In addition, MATLAB frees any memory that was allocated in the MEX-file using the mxCalloc, mxMalloc, or mxRealloc functions.
Consequently, any misconstructed arrays left over at the end of a binary MEX-file's execution have the potential to cause memory errors.
In general, we recommend that MEX-file functions destroy their own temporary arrays and free their own dynamically allocated memory. It is more efficient to perform this cleanup in the source MEX-file than to rely on the automatic mechanism. For additional information on memory management techniques, see the sections Memory Management in Creating C Language MEX-Files and Memory Management Issues.
LAPACK is a large, multiauthor Fortran subroutine library that MATLAB uses for numerical linear algebra. MATLAB uses BLAS, which stands for Basic Linear Algebra Subroutines, to speed up matrix multiplication and the LAPACK routines.
If you want to call a specific LAPACK or BLAS function, you can call the function using a MEX-file. To create a MEX-file, you need C/C++ or Fortran programming experience and the software resources (compilers and linkers) to build an executable file. It also is helpful to understand how to use Fortran subroutines. MATLAB provides the mwlapack and mwblas libraries in the matlabroot/extern/lib folder. To work with complex numbers, MATLAB provides conversion routines in the fort.c and fort.h files in the matlabroot/extern/examples/refbook folder. To help you get started, there are source code examples in the matlabroot/extern/examples/refbook folder.
If you do not know how to use MEX-files, start with the following sections:
For an overview showing how to create and build sample MEX-files, start with the following sections:
To call LAPACK or BLAS functions:
Create a source MEX-file containing the mexFunction gateway routine, as described in the following topics:
Gateway Routine for C language MEX-files.
Gateway Routine for Fortran language MEX-files.
Select a supported compiler for your platform, as described in the following topics:
Build a binary MEX-file using the mex command with one or more of the following options:
Link your source file to one or both of the libraries, mwlapack and mwblas.
Use the -largeArrayDims option because the mwlapack and mwblas libraries support 64-bit integers for matrix dimensions.
If your function uses complex numbers, build your source file with fort.c and include the fort.h header file.
The following topics show how to use the mex command using the example matrixMultiply.c. To work with this file, copy it to a local directory. For example:
copyfile(fullfile(matlabroot, 'extern', 'examples', 'refbook', ...
'matrixMultiply.c'), fullfile('c:', 'work'));The example files are read-only files. To modify an example, ensure the file is writable by typing:
fileattrib('matrixMultiply.c','+w');Building on Windows Platforms. MATLAB provides compiler-specific versions of the libraries on the Windows platform. To link to a specific library, look at the matlabroot/extern/lib/ folder and choose the path for your architecture and compiler. For example, type:
cc = mex.getCompilerConfigurations('Any','Selected');
cc.Manufacturer
computerIf you selected a Microsoft C compiler on a 32-bit platform, MATLAB displays:
ans = Microsoft ans = PCWIN
Link to the libraries in the matlabroot/extern/lib/win32/microsoft/ folder. To simplify the build command, create variables lapacklib and blaslib, which identify the full path and file name of each library.
lapacklib = fullfile(matlabroot, ... 'extern', 'lib', 'win32', 'microsoft', 'libmwlapack.lib'); blaslib = fullfile(matlabroot, ... 'extern', 'lib', 'win32', 'microsoft', 'libmwblas.lib');
When you use a variable to identify the library, you must use the function syntax of the mex command. To build matrixMultiply.c, which uses functions from the BLAS library, type:
mex('-v', '-largeArrayDims', 'matrixMultiply.c', blaslib)To build a MEX-file with functions that use complex numbers, see Handling Complex Numbers in LAPACK and BLAS Functions.
Building on UNIX Platforms. To build the MEX-file matrixMultiply.c, which uses functions from the BLAS library, type:
mex -v -largeArrayDims matrixMultiply.c -lmwblas
To build a MEX-file with functions that use complex numbers, see Handling Complex Numbers in LAPACK and BLAS Functions.
Testing the matrixMultiply MEX-File. To run the matrixMultiply MEX-file, type:
A = [1 3 5; 2 4 7]; B = [-5 8 11; 3 9 21; 4 0 8]; X = matrixMultiply(A,B)
MATLAB displays:
X =
24 35 114
30 52 162
Many LAPACK and BLAS functions modify the values of arguments passed to them. It is good practice to make a copy of arguments you can modify before passing them to these functions. For information about how MATLAB handles arguments to the mexFunction, see Managing Input and Output Parameters.
Example — matrixDivide.c. The following example calls the LAPACK function dgesv that modifies its input arguments. The code in this example makes copies of prhs[0] and prhs[1], and passes the copies to dgesv to preserve the contents of the input arguments.
To see the example, open the file in the MATLAB Editor. To create the MEX-file, copy the source file to a working directory:
copyfile(fullfile(matlabroot, 'extern', 'examples', 'refbook', ...
'matrixDivide.c'), fullfile('c:', 'work'));
To build the file on Windows, type:
lapacklib = fullfile(matlabroot, ...
'extern', 'lib', 'win32', 'microsoft', 'libmwlapack.lib');
mex('-v', '-largeArrayDims', 'matrixDivide.c', lapacklib)To build the file on UNIX type:
mex -v matrixDivide.c -lmwlapack
To test, type:
A = [1 2; 3 4]; B = [5; 6]; X = matrixDivide(A,B)
MATLAB displays:
X =
-4.0000
4.5000
The LAPACK and BLAS functions are written in Fortran. Be aware that C and Fortran use different conventions for passing arguments to and from functions. Fortran functions expect the arguments to be passed by reference, while arguments to C functions are passed by value. When you pass by value, you pass a copy of the value. When you pass by reference, you pass a pointer to the value. A reference is also the address of the value.
When you call a Fortran subroutine, like a function from LAPACK or BLAS, from a C program, be sure to pass the arguments by reference. To do this, precede the argument with an ampersand (&), unless that argument is already a reference. For example, when you create a matrix using the mxGetPr function, you create a reference to the matrix and do not need the ampersand before the argument.
In the following code snippet, variables m, n, p, one, and zero need the & character to make them a reference. Variables A, B, C, and chn are pointers, which are references.
/* pointers to input & output matrices*/ double *A, *B, *C; /* matrix dimensions */ mwSignedIndex m,n,p; /* other inputs to dgemm */ char *chn = "N"; double one = 1.0, zero = 0.0; /* call BLAS function */ dgemm(chn, chn, &m, &n, &p, &one, A, &m, B, &p, &zero, C, &m);
Example — matrixMultiply.c. The matrixMultiply.c example calls dgemm, passing all arguments by reference. To see the source code, open the file in the MATLAB Editor. To build and run this example, see Creating a MEX-File Using LAPACK and BLAS Functions.
You can call LAPACK and BLAS functions from Fortran MEX files. The following example takes two matrices and multiplies them by calling the BLAS routine dgemm:
#include "fintrf.h"
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
mwPointer plhs(*), prhs(*)
integer nlhs, nrhs
mwPointer mxcreatedoublematrix
mwPointer mxgetpr
mwPointer A, B, C
mwSignedIndex mxgetm, mxgetn
mwSignedIndex m, n, p, numel
double precision one, zero, ar, br
character ch1, ch2
ch1 = 'N'
ch2 = 'N'
one = 1.0
zero = 0.0
A = mxgetpr(prhs(1))
B = mxgetpr(prhs(2))
m = mxgetm(prhs(1))
p = mxgetn(prhs(1))
n = mxgetn(prhs(2))
plhs(1) = mxcreatedoublematrix(m, n, 0.0)
C = mxgetpr(plhs(1))
numel = 1
call mxcopyptrtoreal8(A, ar, numel)
call mxcopyptrtoreal8(B, br, numel)
call dgemm(ch1, ch2, m, n, p, one, %val(A), m,
+ %val(B), p, zero, %val(C), m)
return
endCaution Use care when calling level 1 BLAS functions (for example, zdotu, zdotc) with complex numbers in a C program MEX-file. |
MATLAB stores complex numbers differently than Fortran. MATLAB stores the real and imaginary parts of a complex number in separate, equal length vectors, pr and pi. Fortran stores the same complex number in one location with the real and imaginary parts interleaved.
As a result, complex variables exchanged between MATLAB and a Fortran function are incompatible. MATLAB provides conversion routines, mat2fort and fort2mat, that change the storage format of complex numbers to address this incompatibility.
mat2fort — Convert MATLAB complex matrix to Fortran complex storage.
fort2mat — Convert Fortran complex storage to MATLAB real and imaginary parts.
MATLAB supplies the files fort.c and fort.h, which provide routines for conversion between MATLAB and Fortran complex data structures. These files define the mat2fort and fort2mat routines.
To use these routines, you need to:
Include the fort.h header file in your source file, using the statement #include "fort.h".
Link the fort.c file with your program. Specify the full path, matlabroot/extern/examples/refbook for fort.c in the build command.
Use the -Ipathname switch to indicate the header file. Specify the full path, matlabroot/extern/examples/refbook for fort.h in the build command.
When you specify the full path, replace the term matlabroot with the actual folder name.
Handling Complex Number Input Values. It is unnecessary to copy arguments for functions that use complex number input values. The mat2fort conversion routine creates a copy of the arguments for you. For information, see Preserving Input Values from Modification.
Handling Complex Number Output Arguments. For complex variables returned by a Fortran function, do the following:
When allocating storage for the variable, allocate a real variable with twice as much space as you would for a variable of the same size. Do this because the returned variable uses the Fortran format, which takes twice the space. See the allocation of zout in the example.
Use the fort2mat function to make the variable compatible with MATLAB.
Example — Passing Complex Variables. This example shows how to call a function, passing complex prhs[0] as input and receiving complex plhs[0] as output. Temporary variables zin and zout contain the input and output values in Fortran format. To see the example, open the file in the MATLAB Editor. To create the MEX-file, copy the source file to a working directory:
copyfile(fullfile(matlabroot, 'extern', 'examples', 'refbook', ...
'matrixDivideComplex.c'), fullfile('c:', 'work'));
To build the file on a Windows platform, type:
lapacklib = fullfile(matlabroot, ...
'extern', 'lib', 'win32', 'microsoft', 'libmwlapack.lib');
fortfile = fullfile(matlabroot, 'extern', 'examples', ...
'refbook', 'fort.c');
fortheaderdir = fullfile(matlabroot, 'extern', 'examples', ...
'refbook');
mex('-v', '-largeArrayDims', ['-I' fortheaderdir], ...
'matrixDivideComplex.c', fortfile, lapacklib)
To build on a UNIX platform, type:
fortfile = fullfile(matlabroot, 'extern', 'examples', ...
'refbook', 'fort.c');
fortheaderdir = fullfile(matlabroot, 'extern', 'examples', ...
'refbook');
mex('-v', '-largeArrayDims', ['-I' fortheaderdir], ...
'matrixDivideComplex.c', fortfile, '-lmwlapack')
To test:
Areal = [1 2; 3 4]; Aimag = [1 1; 0 0]; Breal = [5; 6]; Bimag = [0; 0]; Acomplex = complex(Areal,Aimag); Bcomplex = complex(Breal,Bimag); X = matrixDivideComplex(Acomplex,Bcomplex)
MATLAB displays:
X = -4.4000 + 0.8000i 4.8000 - 0.6000i
Example — Symmetric Indefinite Factorization Using LAPACK. The example utdu_slv.c calls LAPACK functions zhesvx and dsysvx. To see the example, open the file in the MATLAB Editor. To create the MEX-file, copy the source file to a working directory:
copyfile(fullfile(matlabroot, 'extern', 'examples', 'refbook', ...
'utdu_slv.c'), fullfile('c:', 'work'));
To build the file on Windows, type:
lapacklib = fullfile(matlabroot, ...
'extern', 'lib', 'win32', 'microsoft', 'libmwlapack.lib');
fortheaderdir = fullfile(matlabroot, 'extern', 'examples', ...
'refbook');
mex('-v', '-largeArrayDims', ['-I' fortheaderdir], ...
'utdu_slv.c', fortfile, lapacklib)To build on a UNIX platform, type:
mex -v utdu_slv.c -lmwlapack
Add an underscore character following the function name when calling LAPACK or BLAS functions on a UNIX system. For example, to call dgemm, use:
dgemm_(arg1, arg2, ..., argn);
Or add these lines to your source code:
#if !defined(_WIN32) #define dgemm dgemm_ #endif
[1] Linux is a registered trademark of Linus Torvalds.
![]() | Examples of Fortran Source MEX-Files | Debugging Fortran Source MEX-Files | ![]() |

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 |