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

MATLAB MEX-files

By , 20 Sep 2003
 

Sample Image - mexFunction.jpg

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.

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

EXPORTS
    ; Explicit exports can go here
    mexFunction

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

/def:".\mexFunction.def"

Example

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 "stdafx.h"
#include "Matlab.h"
#include "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))
        {
            y[index]=i;
            index++;
        }

        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;
    /*
        e.g.   
                *x=4,
                *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:

Enjoy!

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.

A list of licenses authors might use can be found here

About the Author

A. Riazi
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
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


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralWell Done!memberbrobie6 Feb '13 - 17:43 
GeneralMy vote of 3memberKoGiot5 Jun '12 - 2:43 
QuestionIs there any way i can generate finctions in C using my code in matlab?memberDeepti koshy12 Apr '12 - 2:28 
GeneralMy vote of 5membermanoj kumar choubey26 Feb '12 - 19:52 
QuestionCreating a dll file for a function of matlabmemberns_v_civil15 Nov '11 - 23:37 
QuestionMex FunctionmemberLinda Mani6 Dec '10 - 19:01 
QuestionCritical Question: >>> How to Call MATLAB in CmemberAjay Dashora17 Mar '10 - 23:54 
GeneralQuestionmemberSaad Shaoor8 Dec '09 - 7:09 
GeneralAOAmembersameen28 Mar '08 - 6:05 
Questionmex-c++-matlab-linking hpp filesmembernishaK443 Nov '07 - 7:18 
QuestionWhere to download this?memberArun.Immanuel25 Apr '07 - 3:28 
Generalneural networkmemberMember #390908510 Mar '07 - 7:43 
Generalusing mex file from Matlab 6.5memberdenoe28 Feb '07 - 0:33 
QuestionCan not include ".h" filememberMember #376555328 Jan '07 - 6:41 
QuestionMex problems with C compilermemberMember #375794724 Jan '07 - 3:41 
QuestionMex problems with a C filememberMember #375794724 Jan '07 - 3:38 
Generalc++ compiler [modified]membernina-matrixware24 Jul '06 - 6:02 
GeneralRe: c++ compilermemberA. Riazi25 Jul '06 - 19:10 
GeneralRe: c++ compilermembernina-matrixware25 Jul '06 - 22:23 
GeneralRe: c++ compilermembernina-matrixware27 Jul '06 - 4:01 
QuestionHow can I run mpgread &amp; mpgwrite [modified]memberh mahjoub5 Jul '06 - 13:58 
QuestionLcc Compilermemberpcardoso7316 Jun '06 - 0:07 
AnswerRe: Lcc CompilermemberA. Riazi16 Jun '06 - 0:14 
GeneralRe: Lcc Compilermemberpcardoso7320 Jun '06 - 5:38 
GeneralMATLAB Compilationmemberfdghgf24 May '06 - 20:16 
AnswerRe: MATLAB CompilationmemberA. Riazi26 May '06 - 2:26 
GeneralDLL LNK2001 Errormemberimahmoud2 May '06 - 3:40 
AnswerRe: DLL LNK2001 ErrormemberA. Riazi4 May '06 - 16:24 
GeneralRe: DLL LNK2001 Errormemberimahmoud4 May '06 - 22:10 
GeneralInvalid MEX-filemembersshain31 Jan '06 - 21:47 
Generalmatlab c++ entry point errormemberprat7822 Jan '06 - 5:20 
QuestionTesting in MATLAB -> testing in C++memberJoJo Qiao10 Jan '06 - 11:27 
QuestionMex file regdmemberMohan Sekar29 Sep '05 - 21:04 
Generalcomm port build failure.memberAjo T18 Sep '05 - 19:52 
Generalmex file structure manipulationmemberAjo T12 Sep '05 - 1:42 
GeneralRe: mex file structure manipulationmemberA. Riazi12 Sep '05 - 1:58 
Generalmex -file: 4-dimensional matricessussR.Tuy25 Aug '05 - 12:24 
Generalneed help in writing a code using mex filememberadepu22 Aug '05 - 18:08 
GeneralFor Mr. A. Riazimemberdenham_matlab12 Apr '05 - 23:36 
GeneralRe: For Mr. A. RiazimemberA. Riazi12 Apr '05 - 23:51 
GeneralRe: For Mr. A. Riazimemberdenham_matlab12 Apr '05 - 23:56 
GeneralCall Intel library from Matlabmemberdenham_matlab11 Apr '05 - 22:48 
GeneralRe: Call Intel library from MatlabmemberA. Riazi11 Apr '05 - 23:06 
GeneralRe: Call Intel library from Matlabmemberdenham_matlab11 Apr '05 - 23:51 
GeneralRe: Call Intel library from MatlabmemberA. Riazi12 Apr '05 - 0:03 
GeneralRe: Call Intel library from Matlabmemberdenham_matlab12 Apr '05 - 3:12 
GeneralCString problems in mexFunctionmemberstaby8 Apr '05 - 10:48 
GeneralRe: CString problems in mexFunctionmemberA. Riazi8 Apr '05 - 16:25 
Generalcall Java objects into MATLABmemberTAN THIAM HUAT20 Mar '05 - 22:26 
Generalbest way to interface a C/C++ dll with Matlabmembertmasquelier11 Jan '05 - 5:31 

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

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