Introduction

MATLAB is a powerful tool for engineering purposes but because of its nature, is very slow in executing functions that take a long time to execute.

For solving this problem, Mathworks provides a toolbox to compile m-files to executable ones. For this reason you can write a script and compile it to an executable with exe extension. But what about functions? Functions could be compiled to other executables called MEX-files. MEX-files in Microsoft Windows have dll extension. Therefore if you have a function like ComputePrimes that computes prime numbers and store them in a matrix, you can compile it to ComputePrimes.dll. Now MATLAB executes this function in less time. MEX-files in other operating systems have other extensions.

As you know, DLL is an abbreviation of dynamic link library and contains variables, functions and classes that are dynamically loaded by the operating system or in this situation by MATLAB. Because they are compiled, they are executed very fast.

Creating MATLAB MEX-file

To create executable files from m-files, you can use MCC. MCC is MATLAB to C/C++ compiler. It can compile m-files to executable files with exe or dll extension. For example:

Make a C translation and a MEX-file for myfun.m:

mcc -x myfun

Make a C translation and a stand-alone executable for myfun.m:

mcc -m myfun

Make a C++ translation and a stand-alone executable for myfun.m:

mcc -p myfun

Make a C MEX wrapper file from myfun1.m and myfun2.m:

mcc -W mex -L C libmatlbmx.mlib myfun1 myfun2

Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (using one MCC call):

mcc -m myfun1 myfun2

But there is another way to create MEX files. In this way you have full control of every function that you created and can optimize their speed, memory, size etc.

The components of a C MEX-file

The source code for a MEX-file consists of two distinct parts:

A computational routine that contains the code for performing the computations that you want implemented in the MEX-file. Computations can be numerical computations as well as inputting and outputting data.

A gateway routine that interfaces the computational routine with MATLAB by the entry point mexFunction and its parameters prhs, nrhs, plhs, nlhs, where prhs is an array of right-hand input arguments, nrhs is the number of right-hand input arguments, plhs is an array of left-hand output arguments, and nlhs is the number of left-hand output arguments. The gateway calls the computational routine as a subroutine.

In the gateway routine, you can access the data in the mxArray structure and then manipulate this data in your C computational subroutine. For example, the expression mxGetPr(prhs[0]) returns a pointer of type double* to the real data in the mxArray pointed to by prhs[0]. You can then use this pointer like any other pointer of type double* in C. After calling your C computational routine from the gateway, you can set a pointer of type mxArray to the data it returns. MATLAB is then able to recognize the output from your computational routine as the output from the MEX-file.

The following C MEX cycle figure shows how inputs enter a MEX-file, what functions the gateway routine performs, and how outputs return to MATLAB.

Creating MEX-files in Visual C++

Run Visual C++, select New... from File menu. In opened dialog, select "Win32 Dynamic-Link Library". In wizard, select "A DLL that exports some symbols" and press finish. Now everything is ready for building a MEX-file!

Create a text file and rename it to your_project.def. your_project is name of your MEX-file. your_project.def is a definition file for exporting symbols. In this situation, you must export mexFunction. Here is an example:

Further reading

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

I was born in Shiraz, a very beautiful famous city in Iran. I started programming when I was 12 years old with GWBASIC. Since now, I worked with various programming languages from Basic, Foxpro, C/C++, Visual Basic, Pascal to MATLAB and now Visual C++.I graduated from Iran University of Science & Technology in Communication Eng., and now work as a system programmer for a telecommunication industry.I wrote several programs and drivers for Synthesizers, Power Amplifiers, GPIB, GPS devices, Radio cards, Data Acqusition cards and so many related devices.I'm author of several books like Learning C (primary and advanced), Learning Visual Basic, API application for VB, Teach Yourself Object Oriented Programming (OOP) and etc.I'm winner of January, May, August 2003 and April 2005 best article of month competetion, my articles are:

I am doing a project in fingerprint identification system to be implemented on an FPGA platform.I have made the matlab code but unfortunately the FPGA software requires the functions to be in C or c++.

I've used a function from matlab library (normrand) in order to generate random numbers with normal distribution. Now I'm going to use such function in my program which is in Visual C#. How could I do this?

Is it correct to create a .dll file with c++ compiler and then use ".net framework" procedures to use a C code in my C# program?

In fact creating a .dll file from a matlab .m file is not still clear for me?Is there anybody who could help me?

I am using MATLAB (version 2009b) and trying to convert a MATLAB user defined function (first.m) to a C shared library (dll) so as to use it in one of the C code in as a function call. Further, the funtion "first.m" calls two other user defined functions ("second.m" and "third.m") with some user defined library function ("one.m" and "two.m"). I have following quarries regarding the conversion of this MATLAB code to C shared library:

1) I am using following command to createa a dll (libFirst.dll) and afterwards I want to compile this created lib file with c code using mbuild. Following command is appropriate:

mcc -t -L C -W lib:libFirst -T link:lib -h first.m libmmfile.mlib

2) Should I create the dll through mcc command for only "first.m" or should I generate the dll by mentioning all "user defined structured functions" on command line? Please note that I will not use the created code second.c and third.c in any program. Please advice...

3) Further, how should I treat the "user defined library functions" for creating the dll and later compilation? Please advice...

4) After creating the dll, I want to call this 'function' in C code. The C code address the input argument vector by 'indv' for evaluating the function. How should I define the variable 'x', which is an array, in the main function of C code for evaluating this "Function"? Please advice....

5) One of the "user defined function" which is important for calculating the "Function" read the value of some data from Excel Sheet (using xlsread). How can I use the xlsread command in External Interfaces? Do I need a additional treatment of this, for successfully calling the "MATLAB written Function" in C code? Please advice...

I need a project that is based on neural networks using any program ( matlab, c++, prolog, n etc).

If you could be of any help i will be very grateful. please.

I'm on a dead line with my projects date. I know I've said on such a short notice but a project on neural networks is hard to find which has not been uploaded on the internet. Kindly help me in this regard please. Thankyou!I will be waiting for you response. email : sameenhkhan@hotmail.com

HiI having some problems with the mex stuff. Im working on a c++ project, which uses the boost libraries, so im includingfiles like the following:#include <boost/numeric/ublas/vector.hpp>But when I try to compile it from matlab, it doesnt workI tried:mex mexi.cpp -L/boostlib/boost/numeric/ublas -lvector.hppand a dozen other similar stuff.Id really be thankful, if smbody could help me, I gotta find this out for my project work and have no clue.Thanks so muchNisha K

Hi.I want to create mex file (.mexw32) from .m file in Matlab 7.1.It seems that it is no longer supported. I used to callmcc -x in Matlab 6.5.1 to generate .dll files that i can runin Matlab. How do I do that in 7.1? Thanks for the help.

hiI appreciate your effort very much. when I compile a mex file in matlab, it could not find all the headers files (.h) needes ... I always have a massege of type " Can not includ ....h file) , althought the h file is placed in the include directory in matlab root .. and in the current directorywould you please help me?best regards

I try to compile the following myfile.c file with the mex functionality of Matlab but it does not work.I get the message:

Mex file entry point is missing. Please check the (case-sensitive)spelling of mexFunction (for C MEX-files), or the (case-insensitive)spelling of MEXFUNCTION (for FORTRAN MEX-files). ??? Invalid MEX-file 'C:\MATLAB71\extern\myfile.mexw32': The specified module could not be found.

How should I write a mexfunction in the .C code?The file myfile.c (performs a statistical test) is the following:

I try to compile the following myfile.c file with the mex functionality of Matlab but it does not work.I get the message:

Mex file entry point is missing. Please check the (case-sensitive)spelling of mexFunction (for C MEX-files), or the (case-insensitive)spelling of MEXFUNCTION (for FORTRAN MEX-files). ??? Invalid MEX-file 'C:\MATLAB71\extern\myfile.mexw32': The specified module could not be found.

How should I write a mexfunction in the .C code?The file myfile.c (performs a statistical test) is the following:

*************************************************************************** Warning: The file extension of 32-bit Windows MEX-files was changed from ".dll" to ".mexw32" in MATLAB 7.1 (R14SP3). The generated MEX-file will not be found by MATLAB versions prior to 7.1. Use the -output option with the ".dll" file extension to generate a MEX-file that can be called in previous versions. For more information see: MATLAB 7.1 Release Notes, New File Extension for MEX-Files on Windows ***************************************************************************

i guess it's something with mex.pl (so that i'd said last time!)i've no idea how i could find the problem of this mex.pl!!!

This error was detected while a MEX-file was running. If the MEX-fileis not an official MathWorks function, please examine its source codefor errors. Please consult the External Interfaces Guide for informationon debugging MEX-files.

If it is an official MathWorks function, pleasefollow these steps in reporting this problem to The MathWorks sothat we have the best chance of correcting it:

1. Send this crash report to segv@mathworks.com for automated analysis. For your convenience, this information has been recorded in: C:\DOCUME~1\TCTTOH~1\LOCALS~1\Temp\matlab_crash_dump.3800

2. Also, if the problem is reproducible, send the crash report to support@mathworks.com along with: - A specific list of steps that will reproduce the problem - Any M, MEX, MDL or other files required to reproduce the problem - Any error messages displayed to the command window A technical support engineer will contact you with further information.

First of all I would like to congratulate you for your articles, that I found to be very good and very informative. The question I have to you is if it is possible to do this exact task using Lcc, instead of Microsoft visual Basic C++ ? The problem is that my company doesn't have VC++, so as we need to call C functions from matlab, I was thinking if it is possible to do this task using other compiler.

In theory you can use LCC, Watcom, Borland and Microsoft compilers. For other compilers than VC++, you must use proper libraries and preprocessors. Just read MATLAB Compiler documents and also refer to its site.