MEX Files – 1

MEX files basically are “Matlab EXecutable” files. As we know, by default Matlab is an interpreted language, and simulation happens by reading instruction by instruction. The MEX files are one option, to write code in a C-like fashion, and then generate an executable (operating system and architecture dependent) which then runs at extremely fast speeds (one of the solutions to Running Long Simulations) So, as mentioned, the executable is always dependent on OS. We shall now split the following discussion, first for Linux, and then for Windows.

On Linux, once the Matlab installation is complete, and assuming you have some version of the GNU C compiler (if you dont, just install it) the job is very easy. The easy way would be to use invoke mex -setup and try to understand what it is actually asking. We would discuss the articles for building Mex files using system ANSI compiler (mexopts.sh). The setup copies the default matlabroot/bin/mexopts.sh to your local home directory. If you open this file, you will notice that it basically contains the name of the C compiler, and other parameters. Currently gcc-4.2 is supported by Matlab. Compilation can be done by calling mex filename.c which generates a filename.mexglx an executable file for Linux machines.

On Windows, you need to get the Visual C++ Express edition maybe 2008 and install it unless you already have a C / C++ compiler. Once you have that installed, running mex -setup asks whether mex should look for compilers. Ask it to, and it should find the relevant compiler. Choose the options, and you are ready to go! Once this is done, write the C-like code for the mex file, and then run mex filename.c from the Matlab command window. This for Windows, generates a filename.mexw32 which indicates its for 32-bit windows machines.

The files generated are the executables, and you are good to go! Just call them like you would for any m file, and they should work. More on how to write this “C-like” code, in the coming posts! For the more enthusiastic, here are the 2 main links where we learnt it from. Functions Reference and MEX-files Guide.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s