Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a Matlab script from C++

Tags:

c++

matlab

I have a C++ program in Visual Studio that records data and saves it into a file. I want to do some Matlab analysis reading from that file and save the results in a separate one. Then, my C++ program keeps going.

Is there any way to do this automatically coding the call in C++ when Matlab is open in the same computer?

Thanks in advance!

like image 607
Slash Avatar asked Aug 20 '15 10:08

Slash


2 Answers

There are many ways to call MATLAB from C++ depending on your needs. Many similar questions have been asked here in the past and I will refer to those and as well give you a solution as your requirement seems to be different.

  1. Do you want MATLAB C or C++ API? Then use mex functions described here, here, here and the actual MATLAB documentation
  2. Do you want to convert your MATLAB program to C++? Then use MATLAB Coder described here, here and here
  3. Do you want to run a MATLAB script from within C++? Then call MATLAB Engine or write a shell script and have that called from C++ described here and here

Your problem falls under the third category. So you need to either call MATLAB engine (See Tal Darom's answer) or write a shell script. I will explain the latter. Lets write a shell script called matlab_script.sh:

#/bin/sh
matlab -nodisplay -nojvm -nosplash < your_matlab_file.m 

then in your C++ code do this:

system("matlab_script.sh");

You need matlab_script.sh to be executable. Under linux you normally do chmod +x matlab_script.sh

like image 141
romeric Avatar answered Oct 02 '22 02:10

romeric


You can start a matlab engine from within a program, and run matlab scripts using matlab engine API.

see documentation at: http://www.mathworks.com/help/matlab/calling-matlab-engine-from-c-c-and-fortran-programs.html

like image 39
Tal Darom Avatar answered Oct 02 '22 03:10

Tal Darom