Matlab MEX compiler setup

Matlab requires compilers for mex -setup langage used (C / C++ / Fortran) 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.

If having trouble with mex -setup for example if setup fails on macOS like:

“sh: /var/folders/…/mex_…: No such file or directory”

Try running the mex -setup command from Terminal using Matlab batch mode to see if Matlab’s shell was breaking setup. This usually fixes the setup issue. In our cases, we found that environment variables MATLAB_SHELL and SHELL were already set appropriately (not the generic /bin/sh), but we still had to run the mex -setup command from Terminal.

matlab -batch "mex -setup C -v"
matlab -batch "mex -setup C++ -v"
matlab -batch "mex -setup Fortran -v"

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 gfortran.exe).Path)).Directory.parent.FullName

This would be something like “C:\msys64\ucrt64”.

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