Click here to Skip to main content
12,254,393 members (60,193 online)
Click here to Skip to main content
Add your own
alternative version


39 bookmarked


, 20 Sep 2003
Rate this:
Please Sign up or sign in to vote.
This article shows you how to create MATLAB MEX-files for improving speed of MATLAB when executing a function.

Sample Image - mexFunction.jpg


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.

C MEX Cycle

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!

Add following lines to main source code:

#include <span class="code-string">"Matlab.h"    //MATLAB API

#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmex.lib")
#pragma comment(lib, "libmatlb.lib")

Add MATLAB_MEX_FILE preprocessor to project settings (Project -> Settings -> C/C++ -> General -> Preprocessor definitions).

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:

; mexFunction.def : Declares the module parameters for the DLL.

LIBRARY      "ComputePrimes"
DESCRIPTION  'ComputePrimes Windows Dynamic Link Library'

    ; Explicit exports can go here

Now you must add following compiler switch to your project (Project -> Settings -> Link -> General -> Project Options):



In this example, input argument is an integer non-complex scalar (n) and output is a vector containing first n prime numbers. Name of MEX-file is ComputePrimes. Syntax:

y = ComputePrime(n)

Final Work:

#include <span class="code-string">"stdafx.h"

Further reading

For more information about MATLAB API, refer to my articles:



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.

A list of licenses authors might use can be found here


About the Author

A. Riazi
CEO Misbah3Com
Iran (Islamic Republic of) Iran (Islamic Republic of)
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:

You can see list of my articles, by clicking here

You may also be interested in...

Comments and Discussions

Generalbest way to interface a C/C++ dll with Matlab Pin
tmasquelier11-Jan-05 5:31
membertmasquelier11-Jan-05 5:31 
GeneralRe: best way to interface a C/C++ dll with Matlab Pin
A. Riazi11-Jan-05 19:06
memberA. Riazi11-Jan-05 19:06 
GeneralOther matlab functions Pin
geekru23-Dec-04 7:49
membergeekru23-Dec-04 7:49 
GeneralRe: Other matlab functions Pin
A. Riazi3-Dec-04 21:47
memberA. Riazi3-Dec-04 21:47 
GeneralTo run matlab file on the CPU without installing matlab Pin
david koh14-Nov-04 4:11
sussdavid koh14-Nov-04 4:11 
GeneralRe: To run matlab file on the CPU without installing matlab Pin
A. Riazi14-Nov-04 4:24
memberA. Riazi14-Nov-04 4:24 
GeneralUsing Matlab functions outside matlab Pin
RulkeCharon31-Oct-04 5:09
memberRulkeCharon31-Oct-04 5:09 
GeneralRe: Using Matlab functions outside matlab Pin
A. Riazi31-Oct-04 5:52
memberA. Riazi31-Oct-04 5:52 
GeneralRe: Using Matlab functions outside matlab Pin
RulkeCharon31-Oct-04 6:24
memberRulkeCharon31-Oct-04 6:24 
GeneralRe: Using Matlab functions outside matlab Pin
Md Jakaria27-Jul-05 22:29
sussMd Jakaria27-Jul-05 22:29 
Generalmex generated by rtw Pin
Andac Tore19-Oct-04 1:05
sussAndac Tore19-Oct-04 1:05 
GeneralRe: mex generated by rtw Pin
A. Riazi19-Oct-04 1:16
memberA. Riazi19-Oct-04 1:16 
QuestionCan you give me a suggestion? Pin
Einly8-Oct-04 17:37
memberEinly8-Oct-04 17:37 
AnswerRe: Can you give me a suggestion? Pin
A. Riazi8-Oct-04 21:08
memberA. Riazi8-Oct-04 21:08 
Generalhelp ! Error in MATLAB Pin
Einly8-Oct-04 0:01
memberEinly8-Oct-04 0:01 
GeneralRe: help ! Error in MATLAB Pin
A. Riazi8-Oct-04 0:14
memberA. Riazi8-Oct-04 0:14 
GeneralRe: help ! Error in MATLAB Pin
Einly8-Oct-04 15:45
memberEinly8-Oct-04 15:45 
GeneralRe: help ! Error in MATLAB Pin
A. Riazi8-Oct-04 21:12
memberA. Riazi8-Oct-04 21:12 
GeneralRe: help ! Error in MATLAB Pin
Einly9-Oct-04 5:47
memberEinly9-Oct-04 5:47 
GeneralRe: help ! Error in MATLAB Pin
A. Riazi9-Oct-04 6:23
memberA. Riazi9-Oct-04 6:23 
GeneralRe: help ! Error in MATLAB Pin
nico76524-Mar-05 0:16
membernico76524-Mar-05 0:16 
GeneralRe: help ! Error in MATLAB Pin
nico76524-Mar-05 0:21
membernico76524-Mar-05 0:21 
GeneralRe: help ! Error in MATLAB Pin
Elise24-Mar-05 6:04
memberElise24-Mar-05 6:04 
GeneralMatlab GUI Pin
Saeid Jafari21-Aug-04 7:15
sussSaeid Jafari21-Aug-04 7:15 
GeneralRe: Matlab GUI Pin
A. Riazi21-Aug-04 23:42
memberA. Riazi21-Aug-04 23:42 
GeneralVery good article Pin
iberg1-Aug-04 13:57
memberiberg1-Aug-04 13:57 
GeneralRe: Very good article Pin
A. Riazi1-Aug-04 22:09
memberA. Riazi1-Aug-04 22:09 
Generalpassing arguments Pin
judekastens29-Jul-04 4:20
sussjudekastens29-Jul-04 4:20 
GeneralErrors Pin
leo775-Jul-04 19:14
memberleo775-Jul-04 19:14 
GeneralRe: Errors Pin
A. Riazi5-Jul-04 20:05
memberA. Riazi5-Jul-04 20:05 
Generalsysquack -&gt; c++ Pin
vesti19-May-04 5:54
sussvesti19-May-04 5:54 
GeneralRe: sysquack -&gt; c++ Pin
A. Riazi19-May-04 23:40
memberA. Riazi19-May-04 23:40 
GeneralkMatlab To C Pin
baselyaser4-May-04 15:57
memberbaselyaser4-May-04 15:57 
GeneralRe: kMatlab To C Pin
A. Riazi4-May-04 17:35
memberA. Riazi4-May-04 17:35 
Generalimporting Mex files into C# Pin
Sampras6-Feb-04 3:30
memberSampras6-Feb-04 3:30 
GeneralRe: importing Mex files into C# Pin
A. Riazi6-Feb-04 17:41
memberA. Riazi6-Feb-04 17:41 
Generalmatlab addin problem Pin
fdgdfgdfghdfg23-Dec-03 15:43
memberfdgdfgdfghdfg23-Dec-03 15:43 
GeneralCreating A MatlabCom For Neural Network Pin
BaijuMax10-Dec-03 20:21
sussBaijuMax10-Dec-03 20:21 
GeneralRe: Creating A MatlabCom For Neural Network Pin
A. Riazi10-Dec-03 23:52
memberA. Riazi10-Dec-03 23:52 
GeneralCompiling with mex Pin
Joyce Turner2-Nov-03 21:50
memberJoyce Turner2-Nov-03 21:50 
GeneralRe: Compiling with mex Pin
A. Riazi3-Nov-03 0:16
memberA. Riazi3-Nov-03 0:16 
GeneralPleonasm Pin
Stlan21-Sep-03 23:27
memberStlan21-Sep-03 23:27 
GeneralUseful for new Matlab&lt;&gt;C devs. Pin
mdgray21-Sep-03 9:23
membermdgray21-Sep-03 9:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160426.1 | Last Updated 21 Sep 2003
Article Copyright 2003 by A. Riazi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid