Setting up Matlab to compile Fortran mex functions on a Mac

I just installed the latest Intel Fortran, version 2021.5.0. I am running macOS Monterey 12.3.1 and Matlab 2019b. I managed to compile a mex function combining a few tricks:

1) At the XQuartz prompt, set the environmental variables for ifort by running the command

source /opt/intel/oneapi/setvars.sh

(Unfortunately, I have not found a good way to avoid running this command every time I want to use ifort.)

2) Start Matlab from XQuartz with the command

/Applications/MATLAB_R2019b.app/bin/matlab &

Here you will have to change the command depending on the version of Matlab you are using

3) grab the modified mex setup xml file attached here, unzip it and save it somewhere where you can find it again --- you can put it with the other setup files under /Applications/MATLAB_R2019b.app/bin/maci64/mexopts, or anywhere else.

The only change I had to make relative to the intel_fortran.xml file that came with the version of Matlab that I am running is at the end of the file. I jsut had to delete a line that was checking for the existence of a library that the latest versions of the linker will find even if they are not in the directory where they are supposed to be. I learned about this issue and solution on from a post on the Apple Developer Forum. This is the modified snippet of the XML file.

<CLANGRT_DIR>

<and>

<cmdReturns name="xcode-select -print-path"/>

<dirExists name="$$" />

</and>

</CLANGRT_DIR>

4) Use the xml file under 3 to run the mex setup with the following command:

mex -v -setup:/Applications/MATLAB_R2019b.app/bin/maci64/mexopts/intel_fortran_luca.xml

Of course, if you have saved it somewhere else, you need to change the path used above

5) Every other time you want to compile a mex function, you will have to repeat steps 1) and 2) above.