Click here to Skip to main content
Click here to Skip to main content


, 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"
#include <span class="code-string">"Matlab.h"
#include <span class="code-string">"mexFunction.h"

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

//return TRUE if n is a prime number
BOOL IsPrime(int n)
    for (int i=2; i<=n/2; i++)
        if (n%i==0)
            return FALSE;

    return TRUE;

void ComputePrimes(double* y, int n)
    int index=0, i=2;

    while (index!=n)
        if (IsPrime(i))


void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
    if (nrhs != 1) 
        mexErrMsgTxt("One input required.");
    else if (nlhs > 1) 
        mexErrMsgTxt("Too many output arguments");

    /* The input must be a noncomplex scalar integer.*/
    int mrows, ncols;
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || 
        !(mrows == 1 && ncols == 1)) 
        mexErrMsgTxt("Input must be a noncomplex scalar integer.");

    double x, *y;
                *y=2, 3, 5, 7
    x = mxGetScalar(prhs[0]);
    /* Create matrix for the return argument. */
    plhs[0] = mxCreateDoubleMatrix(mrows /* 1 */, (int) x, mxREAL);

    y = mxGetPr(plhs[0]);
    //call ComputePrimes subroutines to fill vector of primes
    ComputePrimes(y, (int) x);    

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

Comments and Discussions

Questionis the file "Matlab.h" missing? PinmemberMember 109867471-Aug-14 22:41 
GeneralWell Done! Pinmemberbrobie6-Feb-13 18:43 
GeneralMy vote of 3 PinmemberKoGiot5-Jun-12 3:43 
QuestionIs there any way i can generate finctions in C using my code in matlab? PinmemberDeepti koshy12-Apr-12 3:28 
GeneralMy vote of 5 Pinmembermanoj kumar choubey26-Feb-12 20:52 
QuestionCreating a dll file for a function of matlab Pinmemberns_v_civil16-Nov-11 0:37 
QuestionMex Function PinmemberLinda Mani6-Dec-10 20:01 
QuestionCritical Question: >>> How to Call MATLAB in C PinmemberAjay Dashora18-Mar-10 0:54 
GeneralQuestion PinmemberSaad Shaoor8-Dec-09 8:09 
GeneralAOA Pinmembersameen28-Mar-08 7:05 
Questionmex-c++-matlab-linking hpp files PinmembernishaK443-Nov-07 8:18 
QuestionWhere to download this? PinmemberArun.Immanuel25-Apr-07 4:28 
Generalneural network PinmemberMember #390908510-Mar-07 8:43 
Generalusing mex file from Matlab 6.5 Pinmemberdenoe28-Feb-07 1:33 
QuestionCan not include ".h" file PinmemberMember #376555328-Jan-07 7:41 
QuestionMex problems with C compiler PinmemberMember #375794724-Jan-07 4:41 
QuestionMex problems with a C file PinmemberMember #375794724-Jan-07 4:38 
Generalc++ compiler [modified] Pinmembernina-matrixware24-Jul-06 7:02 
GeneralRe: c++ compiler PinmemberA. Riazi25-Jul-06 20:10 
GeneralRe: c++ compiler Pinmembernina-matrixware25-Jul-06 23:23 
GeneralRe: c++ compiler Pinmembernina-matrixware27-Jul-06 5:01 
QuestionHow can I run mpgread &amp; mpgwrite [modified] Pinmemberh mahjoub5-Jul-06 14:58 
Hi Mr. Riazi
I'v downloaded "mpgread" & "mpgwrite" packages(which are used to convert MPEG video files to matlab standard movie files & vice versa. But when I debug & run makedll.m file & then call mpgread, for example, in matlab command window ([R, G, B] = mpgread('f:\foreman.mpg', [1:20]);) this error message is shown:

Segmentation violation detected at Mon Jul 05 02:52:27 2004
MATLAB Version: (R14) Service Pack 1
MATLAB License: 238685
Operating System: Microsoft Windows XP
Window System: Version 5.1 (Build 2600: Service Pack 2)
Processor ID: x86 Family 15 Model 2 Stepping 9, GenuineIntel
Virtual Machine: Java 1.4.2_04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM
(mixed mode)
Default Charset: ibm-5348_P100-1997
Register State:
EAX = 00000000 EBX = 00000001
ECX = 16131008 EDX = 11081da0
ESI = 0e0fafa4 EDI = 00000006
EBP = 00cddc74 ESP = 00cddc18
EIP = 0e0e774c FLG = 00210246
Stack Trace:
[0] mpgread.dll:0x0e0e774c(1, 0x0e0fafa4, 47, 0x11081d80)
[1] mpgread.dll:0x0e0e4b32(0x11081d80, 0x00cde6ac, 0x0e0faf90, 0)
[2] mpgread.dll:0x0e0e2c6a(0, 0x11081d80, 0x00cde6ac, 0)
[3] mpgread.dll:0x0e0e1cce(3, 0x00cde6ac, 2, 0x00cde70c)
[4] libmex.dll:_mexRunMexFile(3, 0x00cde6ac, 2, 0x00cde70c) + 103 bytes
[5] libmex.dll:public: virtual void __thiscall Mfh_mex::dispatch_file(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(3, 0x00cde6ac, 2, 0x00cde70c) + 157 bytes
[6] m_dispatcher.dll:public: virtual void __thiscall Mfh_file::dispatch_fh(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(3, 0x00cde6ac, 2, 0x00cde70c) + 273 bytes
[7] m_interpreter.dll:int __cdecl mdDispatch(int,char const *,int,struct mxArray_tag * *,int,struct mxArray_tag * *,class Mfh_MATLAB_fn * *)(487, 0x110ff40c "mpgread", 3, 0x00cde6ac) + 88 bytes
[8] m_interpreter.dll:_inDispatchFromStack(487, 0x110ff40c "mpgread", 3, 2) + 801 bytes
[9] m_interpreter.dll:enum opcodes __cdecl inDispatchCall(char const *,int,int,int,int *,int *)(0x110ff40c "mpgread", 487, 3, 2) + 138 bytes
[10] m_interpreter.dll:int __cdecl inInterp(enum inDebugCheck,int,int,enum opcodes,struct inPcodeNest_tag volatile *)(2, 0, 0, 0) + 2359 bytes
[11] m_interpreter.dll:int __cdecl inInterPcodeSJ(enum inDebugCheck,int,int,enum opcodes,struct inPcodeNest_tag *)(2, 0, 0, 0) + 272 bytes
[12] m_interpreter.dll:_inInterPcode(2, 0x78773d54, 0, 0) + 69 bytes
[13] m_interpreter.dll:enum inExecutionStatus __cdecl in_local_call_eval_function(int *,struct _pcodeheader *,int *,struct mxArray_tag * * const,enum inDebugCheck)(0x00cdf2c8, 0x00cdf3b4, 2, 1) + 162 bytes
[14] m_interpreter.dll:$L73181(0x78773d54, 0x0f954cd0 "[R, G, B] = mpgread('f:\foreman...", 0, 0) + 196 bytes
[15] m_interpreter.dll:enum inExecutionStatus __cdecl inEvalCmdWithLocalReturnandtype(char const *,int *,enum inDebugCheck)(0x0f954cd0 "[R, G, B] = mpgread('f:\foreman...", 0, 2, 0x00cdf444 "ôôÍ") + 69 bytes
[16] m_interpreter.dll:_inEvalCmdNoEnd(0x0f954cd0 "[R, G, B] = mpgread('f:\foreman...", 0x00cdf4e4, 0x00cdf49c, 0x01493f28) + 16 bytes
[17] bridge.dll:_mnParser(0x7c80b529, 0x01493f28, 0, 0) + 431 bytes
[18] mcr.dll:public: void __thiscall mcrInstance::mnParser(void)(271268, 0x4d5c3a45, 0x6f6a6861, 0x4d5c6275) + 87 bytes
[19] MATLAB.exe:0x00401d2f(4194304, 0, 271268, 0x01493f28)
[20] MATLAB.exe:0x00403e45(0x00c5dd60, 0x7c90e1fe "¸±", 0x7ffda000, 0x8054a938)
[21] kernel32.dll:0x7c816d4f(0x00403cc0 "jth8U@", 0, 0, 0)
This error was detected while a MEX-file was running. If the MEX-file
is not an official MathWorks function, please examine its source code
for errors. Please consult the External Interfaces Guide for information
on debugging MEX-files.
If it is an official MathWorks function, please
follow these steps in reporting this problem to The MathWorks so
that we have the best chance of correcting it:
1. Send this crash report to for automated analysis.
For your convenience, this information has been recorded in:
2. Also, if the problem is reproducible, send the crash report to 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.
Thank you for your assistance. Please save your workspace and restart
MATLAB before continuing your work.

Please help me to solve the problem.
Thanks in advance & best regards
H Mahjoub
-- modified at 20:01 Wednesday 5th July, 2006
QuestionLcc Compiler Pinmemberpcardoso7316-Jun-06 1:07 
AnswerRe: Lcc Compiler PinmemberA. Riazi16-Jun-06 1:14 
GeneralRe: Lcc Compiler Pinmemberpcardoso7320-Jun-06 6:38 
GeneralMATLAB Compilation Pinmemberfdghgf24-May-06 21:16 
AnswerRe: MATLAB Compilation PinmemberA. Riazi26-May-06 3:26 
GeneralDLL LNK2001 Error Pinmemberimahmoud2-May-06 4:40 
AnswerRe: DLL LNK2001 Error PinmemberA. Riazi4-May-06 17:24 
GeneralRe: DLL LNK2001 Error Pinmemberimahmoud4-May-06 23:10 
GeneralInvalid MEX-file Pinmembersshain31-Jan-06 22:47 
Generalmatlab c++ entry point error Pinmemberprat7822-Jan-06 6:20 
QuestionTesting in MATLAB -> testing in C++ PinmemberJoJo Qiao10-Jan-06 12:27 
QuestionMex file regd PinmemberMohan Sekar29-Sep-05 22:04 
Generalcomm port build failure. PinmemberAjo T18-Sep-05 20:52 
Generalmex file structure manipulation PinmemberAjo T12-Sep-05 2:42 
GeneralRe: mex file structure manipulation PinmemberA. Riazi12-Sep-05 2:58 
Generalmex -file: 4-dimensional matrices PinsussR.Tuy25-Aug-05 13:24 
Generalneed help in writing a code using mex file Pinmemberadepu22-Aug-05 19:08 
GeneralFor Mr. A. Riazi Pinmemberdenham_matlab13-Apr-05 0:36 
GeneralRe: For Mr. A. Riazi PinmemberA. Riazi13-Apr-05 0:51 
GeneralRe: For Mr. A. Riazi Pinmemberdenham_matlab13-Apr-05 0:56 
GeneralCall Intel library from Matlab Pinmemberdenham_matlab11-Apr-05 23:48 
GeneralRe: Call Intel library from Matlab PinmemberA. Riazi12-Apr-05 0:06 
GeneralRe: Call Intel library from Matlab Pinmemberdenham_matlab12-Apr-05 0:51 
GeneralRe: Call Intel library from Matlab PinmemberA. Riazi12-Apr-05 1:03 
GeneralRe: Call Intel library from Matlab Pinmemberdenham_matlab12-Apr-05 4:12 
GeneralCString problems in mexFunction Pinmemberstaby8-Apr-05 11:48 
GeneralRe: CString problems in mexFunction PinmemberA. Riazi8-Apr-05 17:25 
Generalcall Java objects into MATLAB PinmemberTAN THIAM HUAT20-Mar-05 23:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web03 | 2.8.150327.1 | Last Updated 21 Sep 2003
Article Copyright 2003 by A. Riazi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid