MATLAB: How to call/use the MATLAB engine from a Fortran program

compilerengine apifortranMATLABMATLAB Compiler

I'm struggling to get my Fortran code to use the MATLAB engine and run MATLAB scripts/function. I'm using MacOS, gfortran compiler and MATLAB 2019a.
I found an online resource (MATLAB API Guide v5) that describes how to compile the Fortran code:
f77 <include dir> –o <result> <source> <libdir> <libraries>
where:
  • <include dir> is –I<matlabroot>/extern/include
  • <result> is the name of the resulting program
  • <source> is the list of source files
  • <libdir> is –L<matlabroot>/extern/lib/$ARCH (in my case, I'm assuming $ARCH = maci64)
  • <libraries> is –leng –lmx
which does not work for me.
I have added example code samples for MATLAB (saved as testMe.m), Fortran (shortened without error checks and saved as callMat.f90) as well as the complie command:
MATLAB CODE:
a=2;b=3;c=55;d=42;
fprinft("%2.0f + %2.0f = %2.0f", a, c, (a+c));
fprinft("%2.0f x %2.0f = %2.0f", b, d, (b*d));
FORTRAN CODE:
program callMat
#include "engine.h" !not sure if this belongs in/before 'program' or exclude entirely (I've tried all 3 versions).
implicit none
ep = engOpen('matlab ')
engEvalString(ep, 'testMe')
engClose(ep)
end program callMat
GFORTRAN COMPILE COMMAND:
gfortran -I /Applications/MATLAB_R2019a.app/extern/include -o callMat callMat.f90 -L /Applications/MATLAB_R2019a.app/extern/lib/maci64 -leng -lmx
Please could you let me know where I went wrong as I cant even get the example code 'fengdemo.F' working.

Best Answer

In order to check if your installation is correct, please follow the steps given in the link below
f77 <include dir> –o <result> <source> <libdir> <libraries>
where:
  • <include dir> is –I<matlabroot>/extern/include
  • <result> is the name of the resulting program
  • <source> is the list of source files
  • <libdir> is –L<matlabroot>/extern/lib/$ARCH (in my case, I'm assuming $ARCH = maci64)
  • <libraries> is –leng –lmx
These steps are for linux os and might not work as you expect them to
since the engine is not present on mac os.
You can compile your fortran file using mex -client engine Filename.F to compile standalone matlab engine applications.
Related Question