Interface MATLAB code with C, C++, and Fortran
Click here for MATLAB 6.5 (R13) or earlier
- How do I call C or Fortran code from MATLAB?
- How do I call MATLAB from C or Fortran stand-alone programs?
- How do I convert my M-code into a C or C++ shared library?
- How do I know when I would need to buy MATLAB Compiler and when I would need only MATLAB?
How do I call C or Fortran code from MATLAB?
You can call your existing C or Fortran programs from MATLAB by creating MEX-files.
What is a MEX file?
MEX is a built-in utility that enables you to call C or Fortran code in MATLAB by compiling your code into a MATLAB Executable called a MEX-file. MEX-files are dynamically linked subroutines that are called as regular MATLAB functions. This requires you to replace your application's main() with a special gateway function - called "mexFunction" - to pass inputs and outputs to and from MATLAB. MEX is discussed in the MATLAB External Interfaces Guide. For in-depth examples and other detailed MEX information, see the MEX-files Guide, Technical
Note 1605.
To use MEX, you do not need additional MathWorks products; all you need is MATLAB and a supported C or Fortran compiler. On 32-bit Windows, a supported compiler (LCC) is distributed with MATLAB. See Technical Note 1601 for a complete list of supported C compilers.
For example, to compile foo.c into a MEX function, use the following syntax:
mex foo.cThe documentation has several examples of C MEX-files and Fortran MEX-files.
Can I create C++ or Fortran MEX-files?
Yes, you can create C++ MEX-files in MATLAB. For an example, look at file
mexcpp.cppin matlabroot/extern/examples/mex, where "matlabroot" is the root directory of your MATLAB installation.
How do I call MATLAB from C or Fortran stand-alone programs?
The MATLAB Engine allows C or Fortran programs to communicate with a separate MATLAB process via pipes in UNIX and through ActiveX on Windows. For more information on the MATLAB Engine, see using the MATLAB Engine.
How do I convert my M-code into a C or C++ shared library?
You can convert M-code into a C or C++ shared library using the MATLAB Compiler. This shared library can then be incorporated into a Visual Studio project, or be combined with a driver file into a stand-alone application. To compile your M-code, for example foo1.m and foo2.m, into a C shared library use the following syntax:
mcc -B csharedlib:libmyfoo foo1.m foo2.mFor an example on building a C shared library and a driver file, refer to the C shared library example of the documentation. It is further possible to integrate these shared libraries into Visual Studio applications in Visual Studio .NET 2003 and Visual Studio 2005.
How do I know when I would need to buy MATLAB Compiler and when I would need only MATLAB?
If you have C or Fortran code and want to
If you have C or C++ code as well as M-code and you want to
Store