Sie sind auf Seite 1von 86

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 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

SYSTEM SETUP AND CONFIGURATION

MATLAB supports the use of a variety of compilers for building MEX-file

SYSTEM SETUP AND CONFIGURATION

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

SYSTEM SETUP AND CONFIGURATION

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

SYSTEM SETUP AND CONFIGURATION


[1] Lcc-win32 C 2.4.1 in C:\PROGRA~1\MATLAB\R2011b\sys\lcc [2] Microsoft Visual C++ 2010 in c:\Program Files\Microsoft Visual Studio 10.0

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.

COMPILING MEX-FILES WITH MICROSOFT VISUAL STUDIO OR ANOTHER IDE

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.

COMPILING MEX-FILES WITH MICROSOFT VISUAL STUDIO OR ANOTHER IDE

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.

compiling prelinking 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).

compiling prelinking linking.

PRELINK STAGE ON WINDOWS SYSTEMS


The prelink stage dynamically creates import libraries to import the required function into the MEX, MAT, or engine file: - All MEX-files link against libmex.dll (MEX library). - MAT standalone programs link against libmx.dll (array access library) and libmat.dll (MATfunctions). - Engine standalone programs link against libmx.dll (array access library) and libeng.dll for engine functions.

compiling prelinking linking.

LINK STAGE ON WINDOWS SYSTEMS


For the link stage, a mex options file must Define the name of the linker in the LINKER environment variable. Define the LINKFLAGS environment variable that must contain
The switch to create a shared library for MEX-files, or the switch to create an exe for standalone programs. Export of the entry point to the MEX-file as mexFunction for C/C++ or MEXFUNCTION for Fortran. The import library (or libraries) created in the PRELINK_CMDS stage. You can use any other link switch specific to the compiler.

PRELINK STAGE ON WINDOWS SYSTEMS


Set up the linking optimization and debugging switches LINKOPTIMFLAGS and LINKDEBUGFLAGS. Use the same conditions described in the Compile Stage on Windows Systems. Define the link-file identifier in the LINK_FILE environment variable, if necessary. For example, Watcom uses file to identify that the name following is a file and not a command. Define the link-library identifier in the LINK_LIB environment variable, if necessary. For example, Watcom uses library to identify the name following is a library and not a command.

PRELINK STAGE ON WINDOWS SYSTEMS

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.

LINKING DLL FILES TO BINARY MEX-FILES ON WINDOWS SYSTEMS

To link a DLL to a MEX-file, list the DLL's .lib file on the command line.

COMPILING MEX-FILES WITH THE MICROSOFT VISUAL C++ IDE

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.

COMPILING MEX-FILES WITH THE MICROSOFT VISUAL C++ IDE


1.Create a project and insert your MEX source files. 2.Create a .def file to export the MEX entry point. On the Project menu, click Add New Item and select Module-Definition File (.def). For example: LIBRARY MYFILE EXPORTS mexFunction <-- for a C MEX-file or EXPORTS _MEXFUNCTION <-- for a Fortran MEXfile

COMPILING MEX-FILES WITH THE MICROSOFT VISUAL C++ IDE


3.On the Project menu, click Properties for the project to open the property pages. 4.Under C/C++ General properties, add the MATLAB include folder, matlab\extern\include, as an additional include folder. 5.Under C/C++ Preprocessor properties, add MATLAB_MEX_FILE as a preprocessor definition. 6.Under Linker General properties, change the output file extension to .mexw32(../$(ProjectName).mexw32) if you are building for a 32bit platform or .mexw64 if you are building for a 64bit platform.

COMPILING MEX-FILES WITH THE MICROSOFT VISUAL C++ IDE


7.Locate the .lib files for the compiler you are using under matlabroot\extern\lib\win32\microsoft or matlabroot\extern\lib\win64\microsoft. Under Linker Input properties, add libmx.lib, libmex.lib, and libmat.lib as additional dependencies. 8.Under Linker Input properties, add the module definition (.def) file you created. 9.Under Linker Debugging properties, if you intend to debug the MEX-file using the IDE, specify that the build should generate debugging information. For more information about debugging, see Debugging on the Microsoft Windows Platforms.

Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files

THE INGREDIENTS OF A MEX-FILE


All MEX-files must include four things: #include mex.h (C/C++ MEX-files only) mexFunction gateway in C/C++ (or SUBROUTINE MEXFUNCTION in Fortran) The mxArray API functions

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(int nlhs, mxArray *plhs[ ], int nrhs, const mxArray *prhs[ ]) { . }

MEXFUNCTION GATEWAY

Here is what each of the elements mean:

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

THE MXARRAY STRUCTURE CONTAINS, AMONG OTHER THING


1 .The MATLAB variable's name 2. Its dimensions 3. Its type 4. Whether the variable is real or complex an mxArray is declared like any other variable:

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

Some useful routines are:

Introduction Compiling MEX-files MEX-file components MEX-file examples Advanced MEX options Debugging MEX-files C++ MEX-files

WRITING A "HELLO WORLD" MEX-FILE


1.As described in the ingredients section, every MEX-file includes mex.h. Thus, your MEX source should start like this:

#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[]) {

WRITING A "HELLO WORLD" MEX-FILE


3.Add an API function to make the MEX-file do something. The final version of the souce becomes:

#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mexPrintf("Hello, world!\n"); }

Your first MEX-file is complete. Save it as hello.c

WRITING A "HELLO WORLD" MEX-FILE


4.The next step is to tell MATLAB which compiler you want to use to build the MEX-file. You do this with the mex setup command. You can choose the LCC compiler, the C compiler included with MATLAB. This is what it looks like from the MATLAB command prompt:

mex -setup

WRITING A "HELLO WORLD" MEX-FILE


5.Now you are ready to compile and link the MEX-file. You can do this with the following command:

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!

EXAMPLE2: USING API ROUTINES TO WORK WITH MXARRAYS

In the example below, we will create a MEX-file that takes any number of inputs and creates and equal number outputs.

EXAMPLE2: USING API ROUTINES TO WORK WITH MXARRAYS


1. The first job of the MEX-file is to create mxArrays to hold the output data. Each output will be the same size as its corresponding input. This is done using mxCreateDoubleMatrix (creating a matrix to hold doubles), mxGetM (the number of rows the output should be), and mxGetN (the number of columns the output should be).

EXAMPLE2: USING API ROUTINES TO WORK WITH MXARRAYS


2. After the output mxArray is created, the only things left to do is to multiply the input by two, and to put that value into the output array. This is done with mxGetPr (get pointers to the input data and the newly-created output mxArray).

EXAMPLE2: USING API ROUTINES TO WORK WITH MXARRAYS


3. The source code for this example is the enclose files(1)

EXAMPLE2: USING API ROUTINES TO WORK WITH MXARRAYS


4. The MEX-file can now be compiled. mex -setup %choose your C compiler this example) mex timestwo.c %(LCC is fine for

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

[a,b]=timestwo(8) =>error message

EXAMPLE3

Example: Checking inputs and outputs via a MEXfile [a,j]=Example3(9) [a]=Example3(9,8) [a]=Example3(9) =>error

[b]=Example3('k')

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB


1.You have more than 50 input or output variables (MATLAB has a limit of 50) 2. You want to modify many variables using a function, and you don't want to have to type

[a,b,c,d,e,f,g,h,...] = func(a,b,c,d,e,f,g,h,...)

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB


Unlike function MATLAB files, MEX functions have the unique ability to get matrices from the workspace of the calling function, The calling function is the MATLAB file function from which the MEX-file is called.

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB


mxArray *mexGetVariable(const char *workspace, const char *varname); Workspace:Specifies where mexGetVariable searches for array varname. The possible values are: Base:Search for the variable in the base workspace. Caller:Search for the variable in the caller workspace. Global:Search for the variable in the global workspace. Varname:Name of the variable to copy

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB


mxArray *mexGetVariable Returns Copy of the variable on success. Returns NULL in C (0 on Fortran) on failure. A common cause of failure is specifying a variable that is not currently in the workspace. Perhaps the variable was in the workspace at one time but has since been cleared. Examples mexgetarray.c

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB

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> }

EXAMPLE4:EXAMPLE: PASSING ARRAYS BETWEEN MEX-FILES AND MATLAB


mexGetVariablePtr C Syntax #include "mex.h" const mxArray *mexGetVariablePtr(const char *workspace, const char *varname); Arguments:workspaceSpecifies which workspace you want mexGetVariablePtr to search. The possible values are Base :Search for the variable in the base workspace. Caller:Search for the variable in the caller workspace. Global:Search for the variable in the global workspace. Example:mxislogical.c

EXAMPLE5: CALLING MATLAB FUNCTIONS FROM MEX-FILES


There are two functions that allow you to call other MATLAB functions. 1. mexEvalString 2. mexCallMATLAB

EXAMPLE5: CALLING MATLAB FUNCTIONS FROM MEX-FILES

Using mexEvalString

mexEvalString("p=plot(1:10);");

mexevalstring.c

EXAMPLE5: CALLING MATLAB FUNCTIONS FROM MEX-FILES


Other MATLAB functions including built-in functions, MEX-file and MATLAB file functions (not MATLAB file scripts) can be called from within a MEX-file using the mexCallMATLAB function This function accepts five inputs. The first four are structured as integers, exactly the same as the inputs to mexFunction: nlhs, plhs, nrhs, and prhs. The fifth argument is a character string containing the name of the MATLAB function to be called.

EXAMPLE5: CALLING MATLAB FUNCTIONS FROM MEX-FILES


mexCallMATLAB C Syntax int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[], const char *functionName); Returns 0 if successful, and a nonzero value if unsuccessful. Example: mexcallmatlab.c

CUSTOM OPTIONS FILES


The mex script has a set of switches (also called options) that you can use to modify the link and compile stages. For a list with descriptions of switches available, type: mex -help at the MATLAB command prompt.

mex -help

LINKING MULTIPLE FILES

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

GENERAL DEBUGGING STEPS


1.Something bad happens (such as a segmentation fault) 2.Compile with -g. For example mex -g yourmexfile.c 3.Invoke MATLAB through the debugger 4.Turn MEX debugging on (UNIX only) 5.Trace your code until it reaches the issue 6.Use the debugger to investigate 7.Fix the problem 8.Compile without -g 9.Repeat as necessary

SECTION 22: DEBUGGING ON WINDOWS

CONSTRUCTING A SIMPLE MATRIX


The simplest way to create a matrix in MATLAB is to use the matrix constructor operator, []. Create a row in the matrix by entering elements (shown as E below) within the brackets. Separate each element with a comma or space: row = [E1, E2, ..., Em] row = [E1 E2 ... Em] Ex:A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6]

ENTERING SIGNED NUMBERS

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]

SPECIALIZED MATRIX FUNCTIONS

MATLAB has a number of functions that create different kinds of matrice


Fuction ones zeros eye Example A = ones(4, 6, 'uint32') A = zeros(4, 6, 'uint32') A = eye(4, 6, 'uint32')

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)

THE COLON OPERATOR


A = 10:15 A = -2.5:2.5 A = 1:6.3 Also, the default series generated by the colon operator always increments rather than decrementing. A = 9:1 Using the Colon Operator with a Step Value A = 10:5:50 A = 10:2:18 A = 9:-1:1

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

A = 5:5:50 (A = 5:2:20) B = [1 3 6 7 10]; A(B)

SPECIFYING ALL ELEMENTS OF A ROW OR COLUMN


A=magic(4) A(:,2) A(2) A(:,2) sum(A(:, 2)) A(:)

USING LOGICALS IN ARRAY INDEXING


A = [1 2 3; 4 5 6; 7 8 9] B = logical([0 1 0; 1 0 1; 0 0 1]) A(B) find(B)

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

Das könnte Ihnen auch gefallen