Compile c++ code that uses MATLAB Engine in Ubuntu 16.04 , through g++

17 views (last 30 days)
I would like to ask for instructions on how to compile c++ code that uses the MATLAB Engine in Ubuntu 16.04 through g++.
In your answer please use one of the sample codes provided by the default matlab installation for this purpose.

Accepted Answer

Dhruvesh Patel
Dhruvesh Patel on 24 Mar 2017
The Mathworks' documentation for calling MATLAB engine in a C/C++ application is pretty comprehensive and easy to understand. I would suggest that you start with the Getting Started with MATLAB Engine API for C/C++.
The recommended and common workflow for calling MATLAB Engine in C++ application consists of the following steps :
1. Setup the supported compiler for the 'mex' command. You can find the supported compiler for you version of MATLAB by using the page, System Requirements and Supported Compilers. Use the following command in MATLAB Command Window to setup the complier.
mex -v -setup
2. Open the engdemo.cpp file using the following command and copy the file to the current directory.
edit([matlabroot '/extern/examples/eng_mat/engdemo.cpp']);
3. Build the application using the 'mex' command with the compiler we setup in 1.
mex -v -client engine engdemo.cpp
4. Before you can run the compiled application, you will need to modify the 'PATH' and 'LD_LIBRARY_PATH' environment variables.
a) Set the run-time library path. This command replaces the value, if any, in LD_LIBRARY_PATH.
setenv LD_LIBRARY_PATH matlabroot/bin/glnxa64:matlabroot/sys/os/glnxa64
b) Set the path. Make sure that you include the : path terminator character.
setenv PATH matlabroot/bin:$PATH
NOTE: Here matlabroot is the path of the directory where MATLAB is installed. It can be found by executing the command 'matlabroot' on MATLAB Command Window.
5. Run the compiled application.
./engdemo
I would recommend that you refer the following documentation page for more details.
  3 Comments
Stefan Grandl
Stefan Grandl on 10 Jan 2019
I know it's been a while since your question, but in case you still need it:
"If you have multiple versions of MATLAB installed on your system, the version you use to build your engine applications must be the first listed in your Path environment variable. Otherwise, MATLAB displays: 'Can't start MATLAB engine.'
Set the path every time you run MATLAB. Alternatively, place the commands in a MATLAB startup script."
Hope that helps...
Tuan Le
Tuan Le on 7 Feb 2022
@Dhruvesh Patel I am sorry to hijack an old question like this. However, I tried to follow this example with R2021b and can't get it to work. I have posted my question here but didn't get any answer. May I ask for your help?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!