MATLAB Answers

CS
0

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

Asked by CS
on 22 Mar 2017
Latest activity Edited by CS
on 17 Mar 2019
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.

  0 Comments

Sign in to comment.

1 Answer

Answer by Dhruvesh Patel on 24 Mar 2017
 Accepted Answer

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.

  2 Comments

Thanks Dhruvesh for the short tutorial. I followed exactly all the steps. However I am getting this error "Can't start MATLAB engine" which is not informative at all. Is there a way that I can find the root cause of this?
I am testing on a machine with Ubuntu 16.04 and Matlab 2017a, gcc/g++ v4.9 (I am forcing mex to this specific version following the mex warnings on compatible compiler versions).
Any help would be appreciated.
Thanks
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...

Sign in to comment.