From MATLAB to C/C++ Part 1

Dora Boukari
29.07.2021
|
4471
translation of MATLAB algorithms to C++ via the MEX-function

MATLAB Coder Usage

In this paper, we discuss the translation of MATLAB algorithms to C++ language. MATLAB is a high-level language that has proved its feasibility in the past few decades. In fact, it helps scientists to express their work in any mathematical formulas they want to apply. MATLAB also provides a huge number of specific toolboxes for several sophisticated tasks. It is equipped with an interactive environment in which you can simulate, analyze and develop algorithms. A myriad of programming features is also collected in a library to be exploited directly by researchers. All those assets contribute to the importance of MATLAB, especially from the perspective of futuristic scientific research. Unfortunately, speed is not one of MATLAB's assets. This issue highlights many curious questions: What are the assets and the disadvantages of MATLAB? Why is it not as fast as other languages? How can we convert a MATLAB simulation to a C++ script?

Benefits and disadvantages of MATLAB

As we have already mentioned in the previous paragraph, MATLAB is a very practical environment. It is easy to manage, with its ability to prototype rapidly and to provide a clear visualization of mathematical and physical problems. Despite these advantages, MATLAB still has some constraints. For instance, it cannot be implemented directly on processors. In other terms, MATLAB algorithms are not transformable to standalone executables. Furthermore, in certain scenarios where researchers need to merge MATLAB algorithms with existing C++ environments, it is impossible to do so directly because MATLAB cannot work with other source codes and static/dynamic libraries. But our biggest interest in this paper is the slowness and the impotence of MATLAB especially for algorithms with huge numbers of iterations.

Reasons behind MATLAB slowness for iterative algorithms

To understand the reason why MATLAB takes more time to simulate an algorithm than other languages,we need to recognize the difference between a compiler and an interpreter .

Difference between a compiler and an interpreter

A Compiler and an interpreter are two different paths that lead to the execution of a script. They convert the firstly written program to an executable one. But each approach has its own characteristics.

The following table -Table 1- makes a comparison between a compiler and an interpreter properties. It shows the similarities and the differences and explains that we have to classify programming languages, in this perspective, into two categories:

  • Ones that use compilers like COBOL, C++
  • Ones that use interpreters like Virtual Basic, BASIC, Ruby, Perl, and MATLAB
Interpreter Compiler
Similarities
Works on a program of high level to make it treated by the machine Works on a program of high level to make it treated by the machine
Translated the written language to executable one  Translated the written language to executable one 
Helps to debugs errors Helps to debugs errors
Reports errors and checks the program Reports errors and checks the program
Differences
Each time an instruction enters to be treated The whole program enters the compiler at the same time
Control statements are executed in a slow rhythm Control statements are executed in a fast rhythm
No machine code is generated ,works in the high level Generates a machine code, works in the low level (0’s and 1’s)
Efficiency since no machine code is generated (less memory requirements) The machine code is saved in a big memory space (huge memory requirements)
Each time we run the program it will be interpreted instruction by instruction The compilation is done one time when we first enter the source code
At each line interpreted, it reveals the errors and warnings It reveals errors after a global check of the whole program
After reporting errors, the rest of the instructions will not be treated until the error is corrected The whole program is checked
After compilation, the source code is useful After compilation, the source code is not useful

Table: Comparison between the Interpreter and the compiler

PS Some languages are a mixture of both compiler and interpreter such as Java. This is a very successful method to join all the assets of the two different approaches and to gain an intermediate language. For the sake of this paper, we focus only on MATLAB (interpreter) and C/C++ (compiler).

MATLAB: Interpretation language

MATLAB is an interpreted language because the source code is translated and optimized to remove redundancy and to put commands in convenient order to ameliorate the processing speed. This is done with a ‘JIT accelerator’.

The instructions are directly executed, line by line, without any obligation to compile the whole program into a binary code (machine language). It sees each line separately, evaluates, investigates, and runs it in sequence. Each instruction is checked without a compulsory check of the whole program. Being an interpreted language adds to MATLAB an asset of flexibility. The interpreter minimizes redundancy and puts the commands in an opportune order. Hence, the interpreted language is treated and optimized.

C++: A Good Alternative For MATLAB

For some iterative algorithms that require a considerable power of calculation (such as Monte Carlo), a good way to avoid the waste of time is to convert MATLAB scripts to C or C++. In fact, C/C++ are considered as ‘system languages’, unlike MATLAB, because they are not ‘application-based languages‘ and they run faster. Here is an explanation of the discussed hierarchy -Figure(a)-:

Figure(a): Levels of programming languages (MATLAB a high level language, C/C++ lower layer languages)

From MATLAB scripts to C/C++

You may wonder why we don’t just translate our algorithm from MATLAB to C/C++? In fact, system languages and application-based languages are inherently dissimilar. In other words, they will have different functional behaviors. Furthermore, manual translation of code from one language to another is always consuming of both, time and energy. Besides, it brings out errors. This is why automatic translation is a very economic and quick method. The translation is done thanks to the MEX-function.

MEX-function

MEX is the abbreviation of MATLAB Executable. It allows you to generate C (particularly C++ file) from your MATLAB and speed up your simulation. Having a single executable file makes systematic testing much easier.

Practical Implementation

This is a very simple example to explain the efficiency of MEX-function. In fact, while comparing the result of matrix-vector multiple on MATLAB and on C-compiler, C looks so much faster than MATLAB.

Here is a multiplication function for two vector elements, a and b, calculated element by element, written on MATLAB editor

You can use the MATLAB C coder to generate the script in Figure(d) from the script in Figure(b)

Figure (C ):Where to find the MATLAB Coder

Figure(d)Simple function of test in C

Figure(e) Comparing time performance

Looking at Figure(e), it is crystal clear that MATLAB time consumption is almost 6 times bigger than MEX-file consumption.

So as we apply this strategy to bigger programs with a higher level of complexity, the gain of time will be more significant such as Monte Carlo simulation.

More stories

implementation of MATLAB to C/C++ conversion and MEX-functions and simulation method Monte Carlo
MATLAB TO C/C++ Part2

Dive into the Monte Carlo simulation method. Read about specific circumstances for convenient implementation, real implementation of MEX-functions simulated by MATLAB.

Read more
Creating Applications Using Flutter For iOS and Android
Creating Multi-Functional Hybrid Applications Using Flutter For iOS and Android

If you have an app for your business, you must know how difficult it can be to keep your iOS and Android apps consistent and up-to-date with each other. We think Flutter will revolutionize the app in the maintenance process.

Read more
How to use Regular Expressions in Python

Learn how to work with regular expressions in Python to solve pattern-matching problems for which operators may not be enough.

Read more
The Best Python Libraries for Deep Learning

5 best Python libraries for deep learning

Read more
some basics of adding interactivity to a webpage using JavaScript.
Introduction to JS Browser Events for Web Designers

Learn some basics of adding interactivity to a webpage using JavaScript. A new web designer or anyone wanting to revise the basics of JS browser events will find this article helpful.

Read more
create a GPS library model in android
GPS in Android as a Library Module Published on Jitpack via Github. Part 1

How to create a GPS library model in android and add Java class to implement GPS.

Read more

Algo uses cookies for personalization and other purposes. Learn more about cookies use. Algo supports the Digital Advertising Alliance principles. By interacting with this site, you agree to our use of cookies.