Introduction: Making a Matlab MEX File

Picture of Making a Matlab MEX File

Instructions on how to integrate compiled C code with Matlab. MEX stands for MATLAB Executable. MEX-files are dynamically linked subroutines produced from C or Fortran source code that, when compiled, can be run from within MATLAB in the same way as MATLAB M-files or built-in functions. The external interface functions provide functionality to transfer data between MEX-files and MATLAB, and the ability to call MATLAB functions from C or Fortran code.

Here I'll show you everything you need to quickly make a useful mex file.
what you'll need:

= a text editor

= matlab 6.1 or above (earlier versions can do mex files too but slightly different format)

= matlab has it's own c compiler that comes with it, but I used visual c++ compiler cause I had it.

Step 1: The Code

Picture of The Code

download the file I attached: mextest1p0.cpp
cpp stands for c++

.........This is what the code does:.........
it takes a number that you send it from the matlab command prompt.
It prints "hello world" in matlab
it returns two arguments to matlab, a two element number array and a string
the first element of the returned number array is 1 + the number you sent it
the second element of the returned number array is 2 + the number you sent it

..........This is how to implement it:............
save the file to your computer
start matlab
navigate in matlab to the directory where the file is
then follow the compilation and execution instructions at the top of the .cpp file. I can't write these instructions here because instructables auto-edits the commands and makes them appear incorrectly.

In the picture below you can see the code working. Don't worry about the "command line warning", it doesn't seem to effect anything. Notice on the left side, the current directory contains the .cpp file. On the right you can see me compiling the code and then executing it from matlab.


Read through the file in your text editor (for instance notepad in windows), it is very well documented and self explanatory, you will be able to do almost anything you need by following the conventions in the code (i.e. copying and pasting it and making slight modifications)
#######################################################################
........NOTE........
because of some annoying auto-editing that instructables does, the code as seen on the next page WILL NOT WORK, you HAVE TO DOWNLOAD THE FILE I attached instead of copying and pasting this.
########################################################################


Step 2: This Is the Code, DO NOT COPY AND PASTE

Picture of This Is the Code, DO NOT COPY AND PASTE

#######################################################################
........NOTE........
because of some annoying auto-editing that instructables does, the code as seen on this page WILL NOT WORK, you HAVE TO DOWNLOAD THE FILE I attached instead of copying and pasting this.
########################################################################

//This was written in c++ by leevonk
//it is code for a matlab mex file
//the code will take in one number value and output two number values
//the two output numbers are calculated from the input number
//the code will also output a string value
//the code will also print "hello world"

#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, mxArray *prhs[])
{

//##########################################
//#######--print "hello world"--############
//##########################################
mexPrintf("Hello world");

//##########################################
//########--Get Stuff From Matlab--#########
//##########################################
/* declare an array variable to hold the incoming vales */
double* InValues;

/* get the values sent from matlab */
InValues = mxGetPr(prhs[0]);

/* to use these values that were sent from matlab, do InValues[0],InValue[1], etc
according to how many values there are. The InValues will be used below */

//##########################################
//########--Return a number array--#########
//##########################################
/* declare the array that'll be sent to matlab (the * makes it an array) */
double* OutValues;

/* Create/allocate return argument, a 1x2 (1 row 2 column) Matrix
for the return array's first slot (plhs[0]) */
plhs[0]=mxCreateDoubleMatrix(1,2,mxREAL);

/* Get pointer to the return argument */
OutValues = mxGetPr(plhs[0]);

/* assign values to OutValues which will reside in the return array's first slot,
here we're using the InValues to computer the OutValues */
OutValues[0] = InValues[0] + 1;
OutValues[1] = InValues[0] + 2;

//###########################################
//###########--Return a String--#############
//###########################################
/* declare the string variable to be sent to matlab */
char* str;

/* assign a value to the string */
str = "byebye";

/* put the string into the return arrays second slot (plhs[1]) */
plhs[1]=mxCreateString(str);

//############################################
//###########--return more stuff--############
//############################################
/* to return more stuff, follow general rules above but put
the stuff into other plhs slots, plhs[somenumber] */

}

Step 3: If for Whatever Reason It Doesn't Compile

Picture of If for Whatever Reason It Doesn't Compile

If for whatever reason it doesn't compile (it should, works fine on my computer) see these resources, they are where I learned from. They have little glitches (the use some old, nonfunctional grammar, etc) but if you go back and forth between the two you should be able to cobble together something that works.

http://web.ccr.jussieu.fr/ccr/Documentation/Calcul/matlab5v11/docs/00009/009a1.htm

http://cnx.org/content/m12348/latest/

Comments

manojp80 (author)2016-12-06

Which compiler does it need

bakhita11 (author)2016-05-20

well done!!

thank you for sharing the code.

mark.gidney (author)2014-09-27

Thanks, I was having some difficulty but your example fixed me up fine and I managed to make my very first mex file. Mark Gidney, PhD, Canada

sarayut.sutero.5 (author)2014-09-02

Thanks a lot !!! I try to learn how to change from .cpp file to mex file for several days and just succeed in changing from this source. Thanks again for sharing.

leevonk (author)sarayut.sutero.52014-09-02

no problem, I'm glad it helped!

rte3759 (author)2010-09-09

AND, Thanks for the example!!!!!

rte3759 (author)2010-09-09

I get an error in matlab R2009a

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).

Solution is to add the word const in line 78 of mextest1p0.cpp

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])


About This Instructable

43,752views

11favorites

License:

Bio: www.leevonk.com
More by leevonk:WolfPack: Large-Dog CarrierVortex-Drive Micro ROV (ROVVor)Squintasaurus: cybernetic dynamically adjustable vision enhancement system
Add instructable to: