Is there any dependency between Mex and MATLAB Engine?

5 views (last 30 days)
I've written Mex files and I know how it works.
But I'm less familiar with the way MATLAB Engine works. From what I understand, It does invoke a MATLAB command window to execute MATLAB commands through C++ files.
Is there any disadvantage to using MATLAB Engine and not using Mex?

Answers (1)

Madheswaran
Madheswaran on 31 May 2025
Hi Nandini,
MEX and MATLAB Engine are independent APIs that serve different purposes in MATLAB's external language interface.
MEX functions allow you to call C, C++, or Fortran code from within MATLAB. The mex command compiles C/C++ source files (written using MATLAB Data APIs) into binary MEX files that can be called from MATLAB just like built-in functions. This is particularly useful when you want to integrate existing C/C++ libraries into MATLAB or accelerate computationally intensive MATLAB code (using MATLAB Coder).
The MATLAB Engine API enables external applications written in C, C++, Java, Python, or .NET to call MATLAB functions and access MATLAB's computational capabilities. When using C++, you can compile standalone engine applications using the 'mex' command with '-client engine' option. The Engine runs MATLAB as a separate process, which your external application communicates with through pipes (on UNIX) or COM interfaces (on Windows). Make sure to register MATLAB as a COM server if you are on Windows: https://mathworks.com/help/matlab/matlab_external/registering-matlab-software-as-a-com-server.html
You can use MEX when your primary work environment is MATLAB and you need to integrate external code or improve performance. And you can use MATLAB Engine when your main application is in another language and you need to leverage MATLAB's computational capabilities or toolboxes.
For more information, refer to the following documentations:
  1. https://mathworks.com/help/matlab/ref/mex.html
  2. https://mathworks.com/help/matlab/calling-matlab-engine-from-cpp-programs.html
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!