Beruflich Dokumente
Kultur Dokumente
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
INTRODUCTION MEX-FILES
This technical note provides a general overview of MEX-files and a detailed explanation of the external interface functions that allow you to interface C, C++ or Fortran subroutines to MATLAB. MEX-files are a way to call your custom C, C++ or FORTRAN routines directly from MATLAB
MEX-files are a way to call your custom C, C++ or FORTRAN routines directly from MATLAB as if they were MATLAB built-in functions.
INTRODUCTION MEX-FILES
The main reasons to write a MEX-file are: 1.The ability to call large existing C, C++ or FORTRAN routines directly from MATLAB without having to rewrite them as MATLAB files. 2.Speed; you can rewrite bottleneck computations (like for-loops) as a MEX-file for efficiency.
The external interface functions provide functionality to transfer data between MEX-files and MATLAB, and the ability to call MATLAB functions from C, C++ or Fortran code.
GETTING HELP
You can learn more about MEX-files from the http://www.mathworks.com/help/techdoc/matlab_exte rnal/bp_kqh7.html? If you already know how to write a MEX-file, you can also use the http://www.mathworks.com/help/techdoc/apiref/bqoqn z0.html?
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
Once you have verified that you are using a supported C, C++ or FORTRAN compiler, you are ready to configure your system to build MEX-files. In order to do this, run the following command from the MATLAB command prompt: mex -setup
When you run this command, a series of questions are asked regarding the location of the C, C++ or Fortran compiler you would like to use to compile your code. After answering these questions, a MEX options file is created that gives MATLAB all of the information it needs to use your compiler during compilation
TESTING YOUR SYSTEM WITH EXAMPLE MEXFILES Try compiling our sample MEX-file, yprime.c found in the <MATLAB>\extern\examples\mex directory. If you are using C, type the following at the MATLAB prompt to compile the file: mex yprime.c
TESTING YOUR SYSTEM WITH EXAMPLE MEXFILES >> dos('dir'); Volume in drive C has no label. Volume Serial Number is B06E-EE65
Directory of C:\Users\Tung\Documents\MATLAB
10/11/2011 08:19 PM <DIR> . 10/11/2011 08:19 PM <DIR> .. 0 File(s) 0 bytes 2 Dir(s) 26,303,782,912 bytes free
yprime(1,1:4) you should get the following output: ans= 2.0000 8.9685 4.0000 -1.0947
If you do not get this result, or you receive error messages when trying to compile, add a -v flag to your compilation command. mex -v yprime.c This will produce a lot of output (v is for verbose) that shows the compiling and linking process. This may give more information about why the compilation is failing.
Note that you do not have to compile your MEX-file within an Integrated Development Environment (IDE). Using the MEX utility included with MATLAB may easier and will work just as well; using an IDE is just an alternative.
Custom Building on Windows Systems There are three stages to MEX-file building for both C/C++ and Fortran on Windows systems: compiling, prelinking, and linking.
COMPILE
For the compile stage, a mex options file must Set up paths to the compiler using the COMPILER (for example, Watcom), PATH, INCLUDE, and LIB environment variables. If your compiler always has the environment variables set (e.g., in AUTOEXEC.BAT), you can comment them out in the options file. Define the name of the compiler, using the COMPILER environment variable, if needed.
COMPILE Define the compiler switches in the COMPFLAGS environment variable: -The switch to create a DLL is required for MEX-files. -For standalone programs, the switch to create an exe is required. -The -c switch (compile only; do not link) is recommended. -The switch to specify 8-byte alignment. -You can use any other switch specific to the environment.
COMPILE
Define preprocessor macro, with -D, MATLAB_MEX_FILE is required. Set up optimizer switches and/or debug switches using OPTIMFLAGS and DEBUGFLAGS. -If you build in optimization mode (the default), the mex script includes the OPTIMFLAGS option in the compile stage. -If you build in debug mode, the mex script includes the DEBUGFLAGS options in the compile stage. It does not include the OPTIMFLAGS option. -You can include both sets of options by specifying both the optimization and debugging flags to the mex script (OPTIMFLAGS and DEBUGFLAGS, respectively).
Optionally, set up an output identifier and name with the output switch in the NAME_OUTPUT environment variable. The environment variable MEX_NAME contains the name of the first program in the command line. This must be set for -output to work. If this environment is not set, the compiler default is to use the name of the first program in the command line. Even if this is set, you can override it by specifying the mex -output switch.
To link a DLL to a MEX-file, list the DLL's .lib file on the command line.
This section provides information on how to compile source MEX-files in the Microsoft Visual C++ IDE. It is not totally inclusive. This section assumes that you know how to use the IDE. If you need more information on using the Microsoft Visual C++ IDE, refer to the corresponding Microsoft documentation.
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
MEX.H
Every C/C++ MEX-file must include mex.h This is necessary to use the mx* and mex* routines that are discussed in the API functions section of the technical note
MEXFUNCTION GATEWAY
The gateway routine to every MEX-file is called mexFunction. This is the entry point MATLAB uses to access the DLL.In C/C++, it is always:
MEXFUNCTION GATEWAY
MEXFUNCTION GATEWAY The variables prhs and plhs are not mxArrays. They are arrays of pointers to mxArrays. So if a function is given three inputs, prhs will be an array of three pointers to the mxArrays that contain the data passed in The variable prhs is declared as const
THE MXARRAY
The mxArray is a special structure that contains MATLAB data. It is the C representation of a MATLAB array. All types of MATLAB arrays (scalars, vectors, matrices, strings, cell arrays, etc.) are mxArrays
mxArray *myarray;
API FUNCTIONS
mx* functions are used to access data inside of mxArrays. They are also used to do memory management and to create and destroy mxArrays. Some useful routines are:
API FUNCTIONS
mxGetPr and mxGetPi return pointers to their data. To change the values in the array, it is necessary to directly change the value in the array pointed at, or use a function like memcpy from the C Standard Library.
API FUNCTIONS
The API functions mxCalloc and mxFree etc. should be used instead of their Standard C counterparts because the mx* routines let MATLAB manage the memory and perform initialization and cleanup. On the PC there is no concept of stdin, stdout and stderr, so it is important to use MATLAB's functions such as mexPrintf and mexError.
API FUNCTIONS
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
#include "mex.h" 2. Every MEX-file has the mexFunction entry point. The souce now becomes
#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mexPrintf("Hello, world!\n"); }
mex -setup
mex hello.c 6.You can now call the MEX-file like any other MATLAB file by typing its name at the MATLAB command prompt. hello Hello, world!
In the example below, we will create a MEX-file that takes any number of inputs and creates and equal number outputs.
5.Now the MEX-file can be called from MATLAB like any other MATLAB file. For example,
[a,b]=timestwo(3, 8)
a=6 b = 16
EXAMPLE3
Example: Checking inputs and outputs via a MEXfile [a,j]=Example3(9) [a]=Example3(9,8) [a]=Example3(9) =>error
[b]=Example3('k')
[a,b,c,d,e,f,g,h,...] = func(a,b,c,d,e,f,g,h,...)
mexGetVariablePtr similar to mexGetVariable, but instead of making a copy of the array, a pointer to the original array is returned
const mxArray *myarray; if ((myarray = mexGetVariablePtr("a", "base"))==NULL) mexErrMsgTxt("Variable 'a' not in workspace."); else { <do stuff with mymatrix> }
Using mexEvalString
mexEvalString("p=plot(1:10);");
mexevalstring.c
mex -help
It is possible to combine several object files and use object file libraries when building MEX-files. To do so, simply list the additional files with their full extension, separated by spaces. For example, on Windows:
mex -help
mex circle.c square.obj rectangle.c shapes.lib is a legal command that operates on the .c, .obj, and .lib files to create a MEX-file called. The base name of the resulting MEX-file is taken from the first file in the list.
circle.mexw32
When entering signed numbers into a matrix, make sure that the sign immediately precedes the numeric value. Note that while the following two expressions are equivalent, Ex1: [7 -2 +5] Ex2:- [7 - 2 + 5]
magic rand
randn randperm
M = magic(3) randi(100,2,5)
randn(3) randperm(3)
CONCATENATING MATRICES
A = ones(2, 5) * 6; 2-by-5 matrix of 6's B = rand(3, 5); C = [A; B]
CONCATENATING MATRICES
Cat :Concatenate matrices along the specified dimension V d: A = ones(2, 5) * 6; 2-by-5 matrix of 6 B = ones(2, 5) * 2; 2-by-5 matrix of 6 cat(1, A, B) cat(2, A, B) vertcat(A, B) A = [8 1 6; 3 5 7; 4 9 2] repmat(A, 2, 4)
MATRIX INDEXING
A = magic(4) A(4, 2) A(1,4) + A(2,4) + A(3,4) + A(4,4)=sum(A(1:4, 4)) B=A B(1:3:16)=B(1:3:end) = -10 (element at index 0,3,6,9,12,15) Will be assigned with the value -10
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files
Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files