Matlab Engine Tutorial with Demo Code

This tutorial will explain you how we can use any of the matlab function from C or C++ program.

"Calling any of the Matlab functionality through Matlab engine"

This is the common concern among the community who often uses Matlab or any C/C++ library for some computation and calculation.

It is easy to code complex algorithms in Matlab as Matlab has already implemented most of the algorithms, so if you want to code some algorithm in C/C++ , Do you really want to code it from scratch ?.  What if it is already there in Matlab can i use it?

Yes you can , you can access any of the Matlab functionality  by using Matlab engine.

I created a sample framework for matlab engine application download it from here .
Extract it.

matlab_engine_demo folder contains four subfolders.

-bin  
-build
-cmake
-src

change following things in  ~/cmake/FindMatlab.cmake

go to the line INCLUDE_DIRECTORIES(/media/lokender/phdwork/mat14/extern/include)

change  "/media/lokender/phdwork/mat14/extern/include"  to  path_to_your_matlab_installation/extern/include



bin - contains generated binary files and matlab m-files. you can call any m files from c/c++  program.
build- This folder contains all build files.
cmake- This folder contains cmake setting for matlab specific libraries and directories.
src  - This folder contains all source files.


Steps to create a new matlab engine application.
1. Put your src files inside src folder.
2. Edit cmakelist (only if there is any additional dependency).

Steps for compiling 
1. cd to ~/matlab_engine_demo/build
2. cmake ..
3. make


Steps for running
1. Go to ~/matlab_engine_demo/bin
2. ./application_name

Sample Application:

you can pick any of the sample file from  ~matlab_installation_directory/extern/examples/eng_mat
put it in the src folder. (Modify it according to your functionality or you can write it by your own from scratch)

There is a cmakelist file in src folder open it and change the name of project and executable.

matlab_engine_demo to your_project_filename

INCLUDE_DIRECTORIES(${MATLAB_INCLUDE_DIR})
add_executable (matlab_engine_demo matlab_engine_demo.cpp)
target_link_libraries(matlab_engine_demo ${MATLAB_LIBRARIES})

Run as mentioned above .

Share this post and spread the knowledge --->

No comments:

Post a Comment