Home > Academic, Matlab > A Short MEX Tutorial and Demo

A Short MEX Tutorial and Demo

Matlab is a great programming language/environment because of its ease of use, great visualization, and rapid prototyping abilities. Raw speed is not one of its strong suits. MEX (Matlab Executables) are the answer. These functions allow you to program in C or C++ (ultra fast languages), but be able to call and use them from Matlab programs. This post is a short intro to mex files which should get you up and running.

What This Post Teaches

In this post, I show how to create a mex file, how to set up inputs and outputs, how to get access to Matlab objects, and how to manipulate them. I also give a skeleton mex program that might be helpful. There is a lot more to learn, and I’d refer you to the mex manual regardless.

What You Should Already Know

I’m going to assume you already know how to program in C, and already know how to program in Matlab. This post does not teach either language, but will show you how to use them together to get the best of both worlds.

Hello world!

Lets get started. First, type:
>>mex -setup
Then go through the menus to select a compiler that you have installed on your system. I use gcc on linux, visual studios on windows, and mexopts on mac. Now, create a file called, “helloworld.cpp” and we’ll start coding. In this first example, pay attention to the signature of the mexFunction. This signature is always the same.

#include <math.h>
#include <matrix.h>
#include <mex.h>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  mexPrintf("Hello World!\n");

Save the file, and in the Matlab prompt type,
>>mex helloworld.cpp
If all goes well, you should get the following when you run helloworld:
>>Hello World!

Setting Up Inputs and Outputs

Now that we have a working program, the next step is to get inputs and outputs going so we can do something useful. The mxArray pointers plhs and prhs represent a pointer to the left hand sside and a pointer to the right hand sside respectively. The left hand side are the outputs and the right hand side are the inputs.

put something like this in the top of mexFunction:

  //declare variables
  mxArray *a_in_m, *b_in_m, *c_out_m, *d_out_m;
  const mwSize *dims;
  double *a, *b, *c, *d;
  int dimx, dimy, numdims;
  //associate inputs
  a_in_m = mxDuplicateArray(prhs[0]);
  b_in_m = mxDuplicateArray(prhs[1]);
  //figure out dimensions
  dims = mxGetDimensions(prhs[0]);
  numdims = mxGetNumberOfDimensions(prhs[0]);
  dimy = (int)dims[0]; dimx = (int)dims[1];
  //associate outputs
  c_out_m = plhs[0] = mxCreateDoubleMatrix(dimy,dimx,mxREAL);
  d_out_m = plhs[1] = mxCreateDoubleMatrix(dimy,dimx,mxREAL);

Accessing and Manipulating Matlab Objects

To access the variables, you need to associate a pointer to the data in the mxArray. Once you do this, accessing the variables is very simple.

  a = mxGetPr(a_in_m);
  b = mxGetPr(b_in_m);
  c = mxGetPr(c_out_m);
  d = mxGetPr(d_out_m);

Now it is possible to access the arrays with standard C or C++ [] notation. There are three important things to remember though:

  • You use 0-based indexing as always in C
  • You still use column-first indexing like in Matlab, though
  • To access the arrays, you use linear indexing (you can’t use [x][y], you have to use [y+x*dimy]

With those three things in mind, go crazy. You can use standard C libraries (as long as you include them). You can use for loops as much as your heart desires, and your code will be much, much faster than its Matlab equivalent.


Download this starter file (demo.cpp). This has all of the features discussed in this post, and should be a good primer for any mex function. Give it a try. Tell me what you think, and let me know if any improvements are needed.


To run the demo, download the .cpp file, then at the prompt run:

  >>mex demo.cpp
  >>a = round(rand(2)*10)
  >>b = round(rand(2)*10)
  >>[c,d] = demo(a,b)

Categories: Academic, Matlab Tags: ,
  1. January 29th, 2009 at 12:58 | #1

    It was great help, thanks for nice demo.
    Could you please inform me on possible mex file references, or a user guide?


  2. Davids
    March 11th, 2009 at 19:15 | #2

    Thank you for your short MEX tutorial

    If I have 10 file.c connect between them, what will be written in the MATLAB command to compile the file that I want to execute.
    for example for one file you have written “mex demo.cpp”

    Thank you

  3. April 29th, 2009 at 09:54 | #3

    To compile multiple c files use

    >>mex file1.c file2.c file3.c

  4. Anonymous
    August 11th, 2009 at 03:54 | #4

    im using ubuntu 9.04 jaunty. gcc only failed to compile the *.cpp because it needs g++ compiler. so i installed the compiler and it worked well. thx

  5. August 11th, 2009 at 09:38 | #5

    Interesting. I’m glad you got it working, though!

  6. Samir Ben Abid
    August 20th, 2009 at 05:47 | #6

    Thank you for this great tutorial :)

  7. Dongcai su
    October 16th, 2009 at 22:24 | #7

    Hi lankton:
    Your briefly written tutorial is very helpful, but I believe that you had missed something: “Free up the dynamically located memory.” which is:

  8. October 20th, 2009 at 10:06 | #8

    @Dongcai su
    Great addition.
    mxFree is used in conjunction with mxCalloc
    mxDestroyArray is used in conjunction with Array objects such as those created by mxCreateDoubleArray.

  9. terrance
    November 16th, 2009 at 16:00 | #9

    Hi Shawn, Why if Matlab stores matrices as column major is the ‘linear’ scheme to address specific values of a matrix in row major fashion; e.g. [x][y], you have to use [y+x*dimy], assuming x = Nrows and y = Ncols.

  10. busy_bee
    February 6th, 2010 at 10:47 | #10

    I have written a code to add two numbers in mex. but the code complies successfully but cannot run it can some help me
    thanks in regard

    #include “mex.h”
    #define a_IN prhs[0]
    #define b_IN prhs[1]
    #define c_OUT plhs[0]
    void mexFunction( int nlhs, mxArray *plhs[],
    int nrhs, const mxArray*prhs[] )
    double *a,*b,*c;
    a = mxGetPr(a_IN);
    b = mxGetPr(b_IN);
    c = mxGetPr(c_OUT);
    *c = *a + *b;

  11. tabraiz
    March 12th, 2011 at 20:32 | #11

    Though matlab successfully done the mex setup still there an error appears
    ??? Error using ==> mex at 208
    Unable to complete successfully.

  12. tabraiz
    March 12th, 2011 at 20:33 | #12

    I am using Visual Studio is there any other setting we have to do

  13. abdallah
    April 21st, 2011 at 09:09 | #13

    is there a possibility to debug .c or .cpp code from matlab?

    thanks in advance

  14. April 21st, 2011 at 10:30 | #14

    @abdallah Don’t know of a really snazzy debug tool… Would be cool if someone suggests one! I always use old-school debugging techniques like printfs and commenting out blocks of code.

  15. Suhas
    May 18th, 2011 at 14:56 | #15

    The URL to the mex manual is broken. Can you re-link to a correct URL if you know one? Else, do you have a local copy that you can share? Will just save a quick Google. :)

  16. amit
    July 15th, 2011 at 02:23 | #16

    It was excellent demo.Just give details for running mex file.I struggled lot gor first time.
    1)first save demo.cpp file in current working directory as we save images.
    2)type mex -setup on MATLAB command prompt.
    3)follow the procedure and select your version(like visual studio)
    4)then type, mex demo.cpp ans press enter
    5)your file will compile now.
    6)now give input like a=[1 2 3;4 5 6;7 8 9]; and b=[1 2 3;4 5 6;7 8 9];
    7)type [c d]=demo(a,b) and see magic of SHAWN.
    Thanks a lot SHAWN again.

  17. July 20th, 2011 at 00:25 | #17

    how to covert c to matlab files

  18. amit
    July 27th, 2011 at 04:29 | #18

    it is not necessary to convert c to matlab files. Just write programme,save it as .cpp and compile using matlab.@chitra

  19. Name Not Required
    May 21st, 2012 at 11:47 | #19

    Really Nice work.

  20. Anonymous
    May 28th, 2012 at 09:33 | #20

    >> tic; [c,d] = helloworld(a,b); toc
    element[0][0] = 8.000000
    element[1][0] = 9.000000
    element[0][1] = 1.000000
    element[1][1] = 9.000000
    Elapsed time is 0.000605 seconds.
    >> tic; [c,d] = helloworld_m(a,b); toc
    element[1][1] = 8
    element[2][1] = 9
    element[1][2] = 1
    element[2][2] = 9
    Elapsed time is 0.002685 seconds.

    Takes 22.53% of the time spent with the same code in a .m function. Definitely gonna use it from now on.

  21. brkzr
    June 8th, 2012 at 17:01 | #21

    Thank you!

    July 13th, 2012 at 15:16 | #22

    I ve been trying the given code but it compiles and nothing happens .


    other program

    I tried again and again but no output.

  23. saloni
    December 12th, 2012 at 04:19 | #23

    Hello Sir,I have a mex function(FMReDistSDF_mex.c)
    I have to compile this and use it as matlab function in another program.I am nt exactly getting the steps to do dis..plz help me out..

  24. January 18th, 2013 at 06:48 | #24

    Thank you for this tutorial. I knew that sooner or later I would had to deal with C on matlab and… well, this helped a lot! :)

  25. notprimal
    March 31st, 2013 at 19:25 | #25

    Thanks you very much, super useful.
    Matlab documentation is totally useless for this.

  26. Tarek Sakakini
    June 19th, 2013 at 12:17 | #26

    Thank you. Very much helpful.

  27. July 3rd, 2013 at 09:56 | #27

    You need the matlab compiler package. Your .m will be converted to .h and .c, and then compiled into .exe. Can even compile standalone GUIs. Use the mcc command.

  28. Serhan Gul
    August 19th, 2013 at 08:51 | #28

    Great introduction to using mex. Thanks a lot!

  29. Hariprasad Rao
    August 28th, 2013 at 05:30 | #29

    Hello Shawn, how to find an array’s size inside Mex. i have something like i add some value into an array if a criteria is fulfilled.
    Myarray is int array
    i tried mxGetNumberOfElements(Myarray) but i get an error like
    “assignment of pointer to const incomplete struct mxArray_tag defined at line number to pointer to int”

  30. Flight Engineer
    February 15th, 2014 at 14:35 | #30

    Thank you very much, It helped a lot.

  31. August 23rd, 2014 at 15:06 | #31

    Thank you very much for all the helps… I’d like to know how to call in MatLab a *.dll library written and compiled in C++ and another in java. Thanks.

  32. Fareeha Mahmood
    October 4th, 2014 at 14:48 | #32

    Is there any way to connect Keil uvision5 with MATLAB directly. i want to get input from Keil to MATLAB.
    Thanks in advance..

  33. lulu
    May 2nd, 2015 at 11:21 | #33

    Hi, thanks for the tutorial ! . Any idea why my function gets stuck ? It seems to be the same issue that in the following link, but I am using mxDestroyArray, and memory doesn’t seems to free. Cheers.


    #include “mex.h”
    #include “matrix.h”

    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    mxArray *x_in_m,*y_in_m, *time_out_m ;
    double *x, *y,*time ;
    int N ,i ;
    x_in_m = mxDuplicateArray(prhs[0]);
    y_in_m = mxDuplicateArray(prhs[1]);
    x = mxGetPr(x_in_m);
    y = mxGetPr(y_in_m);
    N = mxGetNumberOfElements(prhs[0]);
    time_out_m = plhs[0] = mxCreateDoubleMatrix(N,1,mxREAL);
    time = mxGetPr(time_out_m);
    for(i = 0; i < N ; i ++ ) { time[i] = (double)i;}

  34. Francisco López de la Franca
    September 10th, 2015 at 06:03 | #34

    I need to call from Matlab a C++ method that receives as input a C++ object, specifically, I’ve got a C++ code that uses the ITK library (in C++) and receives as input an itk::Image (N-dimensional) object.
    All the code I’ve seen so far passes standard C typed arguments from Matlab to C++ and viceversa, so is it possible to do what I have proposed earlier, that is, convert Matlab object (e.g. Matlab image) to C++ objects?
    Thank you very much.
    Kind regards.

  35. Terry
    November 28th, 2015 at 04:11 | #35

    Shawn – I’m a real newcomer to this but I have a problem. I have some C code which compiles fine with the gcc compiler using
    gcc -lstdc++ program.c -o program
    But when I use mex I can’t see how to link in the c++ library
    Any help much apreciated

  1. January 5th, 2011 at 21:53 | #1
  2. August 5th, 2011 at 11:10 | #2
  3. July 25th, 2012 at 10:10 | #3


buy discount viagra
buy price viagra
buy real viagra online
buy viagra in boston
buy discount soma
buy viagra with discount
buy viagra 100mg
buy now viagra
buy cheap viagra
buy viagra online
cheapest cialis
buy levitra now
buy viagra new york
buy discount levitra
online pharmacy
buy now cialis
buy levitra now
cheapest cialis
Pfizer viagra free samples
buy viagra san antonio
cheap viagra online
buy viagra new york
buy viagra internet
cheapest cialis