How do I compile and run a C MEX-file?
MATLAB is shipped with a bunch of example MEX-files -- they should be located in the folder $MATLAB/extern/examples/mex.
Note: $MATLAB refers to the root directory where MATLAB is installed on your system.
One of the files in this folder should be yprime.c. To run "yprime.c", do the following:
- CD into the folder $MATLAB/extern/examples/mex
- Type "mex yprime.c" at the MATLAB command prompt to compile it
- If you type "ls" in MATLAB now, you should see a yprime.dll in the folder
Here's the sequence of commands again, as typed at the MATLAB command prompt (here I'm using MSVC/C++ 5.0 compiler):
» cd D:\MatlabR11\extern\examples\mex
» pwd
ans =
D:\MatlabR11\extern\examples\mex
» ls yprime*
yprime.c
» mex yprime.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 11.00.7022 for 80x86
Copyright (C) Microsoft Corp 1984-1997. All rights reserved.
» ls yprime*
yprime.c yprime.dll
» yprime(2, [1 2 3 4])
ans =
2.0000 8.9685 4.0000 -1.0947
»
If you are unable to get the above, check the following:
- Are you in $MATLAB/extern/examples/mex?
- Is there a "yprime.c" in this folder?
- Did you do "mex -setup"?
- Is your MATLAB path and your compiler path defined correctly in the options file (mexopts.bat)?
- Is your $MATLAB/bin and $MATLAB/extern/include on the system path? On Windows NT, this can be done as follows:
- Go to "Control Panel"
- Double-click on "System"
- Select the "Environment" tab
- Under "User Variables for ...", select "Path"
- Go to the end of the "Value" field at the bottom of the window, and add $MATLAB/bin and $MATLAB/extern/include, separated by a semi-colon. Remember: $MATLAB refers to the root directory where MATLAB is installed on your system; use the actual path to MATLAB and not $MATLAB.