Matlab MEX compiler setup
Matlab requires C / C++ / Fortran compilers for mex
and Matlab Engine for the respective code language.
Windows Matlab supported
compiler
locations are communicated to Matlab via environment variables.
One-time setup MEX:
mex -setup C
mex -setup C++
mex -setup Fortran
Inspect Matlab MEX parameters:
mex.getCompilerConfigurations('c')
mex.getCompilerConfigurations('c++')
mex.getCompilerConfigurations('fortran')
It’s possible to switch between compilers that are setup with MEX. Choosing compilers is generally not possible on Linux or macOS from within Matlab. If a oneAPI version compatible with Matlab is installed on Windows, Matlab may detect it and allow switching compilers. If a different compiler is detected and allowed by Matlab, commands to choose the compiler will be at the bottom of the output when using the “mex -setup” commands below.
Once MEX is working, consider using Matlab buildtool build system for simple, terse syntax to build and test MEX and Matlab Engine code.
Windows MinGW MEX
Using MinGW on Windows with Matlab requires having an exact version of MinGW supported by Matlab. For example, the version of MinGW with MSYS2 is generally not supported by Matlab.
Tell Matlab the supported MinGW compiler path via Windows environment variable MW_MINGW64_LOC.
Find the MinGW compiler location from PowerShell:
(Get-Item((Get-Command gcc.exe).Path)).Directory.FullName
Put that path in Matlab:
setenv('MW_MINGW64_LOC', '<path of gcc.exe>')
Do “mex -setup” as above.
C MEX Example
Compile built-in C example
mex(fullfile(matlabroot,'extern/examples/mex/yprime.c'))
Run
yprime(3, [4,2,7,1])
ans = 2.0000 5.9924 1.0000 2.986
Fortran MEX example
Compile built-in Fortran example:
mex(fullfile(matlabroot,'extern/examples/refbook/timestwo.F'))
Run:
timestwo(3)
ans = 6.0