Generating C code from MATLAB algorithms

MathWorks Australia
By Arvind Ananthan, product marketing manager, MathWorks
Wednesday, 25 July, 2012


Exploration of design ideas is the foundation of any design workflow. It helps create compelling products with unique value propositions that separate them from the competition.

For engineers, idea exploration takes the form of prototyping and testing algorithm variations to evaluate their behavioural and functional effect on the final product design.

Such evaluation narrows the set of algorithm alternatives and helps identify the one that eventually make its way into the design of the entire system.

The speed with which an engineer can design and assess algorithm variations is critical to efficient optimisation of the design. The high-level interpreted language of MATLAB is a choice for engineers to express their ideas during design exploration, because it lets them focus on algorithm behaviour instead of low-level programming details.

As product development evolves from algorithm exploration to system design, integration and implementation on hardware, the design specifications are typically translated by hand into a language such as C or C++.

The C programming language has broad popularity and is widely accepted as the language of choice for many development phases including system design, application software development and embedded software implementation.

C programming

Often engineers translate MATLAB algorithms to C/C++ code to create stand-alone software prototypes, integrate MATLAB algorithms with other software written in C/C++ or deliver specifications to embedded software engineers for implementation. Generating C automatically (and nearly instantly) from MATLAB speeds design exploration and product development iterations.

The pitfalls of manual translation stem from differences in the programming paradigms of MATLAB and C. MATLAB has a succinct syntax and native data types for the vector and matrix processing operations used in embedded signal processing and control algorithms. The equivalent C code requires multiple loops to process individual data samples, resulting in many lines of C code for a single line of MATLAB code.

Equally important, the polymorphic and dynamically typed behaviour that makes MATLAB flexible and easy to use is not readily accessible in the more statically typed C language without detailed programming. These differences make manual translation a time-consuming and complex process.

Manual translation also results in multiple copies of the same algorithm written in different languages. The engineer must verify that these copies remain equivalent throughout multiple design iterations.

The cost of verifying and updating revisions to accommodate requirement changes quickly becomes prohibitive, often resulting in errors and a design that diverges from the original specification.

Automating translation of MATLAB code to C code overcomes most, not all, of the problems associated with manual translation. Automatic MATLAB-to-C code generation offers these advantages:

  • Design engineers spend more time innovating and tuning high-level algorithms in MATLAB rather than writing and debugging low-level C code;
  • The equivalence of MATLAB algorithms and generated C code is easily maintained during design iterations;
  • C code is produced much faster and is free of the errors that are frequently introduced by hand coding.

The automatic translation workflow from MATLAB allows engineers to maintain ‘one truth’ - and elaborate it directly within MATLAB to incorporate implementation details such as specifying data types and sizes of input and output variables.

automatic translation

Design iterations become easier because engineers continue to use the interactive debugging and visualisation capabilities in MATLAB throughout the process.

The cost of producing and verifying handwritten C code can be eliminated for common design workflow uses such as prototyping algorithms as stand-alone executables, integrating algorithms as re-usable libraries and accelerating parts of the algorithm’s execution in MATLAB.

Translating MATLAB code to C code (automatically or by hand) involves making decisions on multiple implementation details in the algorithm such as data type management, fixed-point maths support and static/dynamic memory allocation.

Choices made by engineers when working with these details help satisfy various implementation requirements and enable the engineers to manage trade-offs between reducing memory footprint and improving processor use or performance.

As an automatic MATLAB to C code generation tool, MATLAB Coder enables engineers to specify these requirements and make implementation decisions directly within MATLAB. This makes it easier to maintain one reference design and iterate on the evolving design in MATLAB.

The following sections of this article describe the recommended three-step workflow that enables engineers to specify the implementation details that are needed to convert their MATLAB algorithms into the desired C code and verify the resulting code against their original MATLAB specification. This workflow is illustrated in the figure below.

prepare test generate C/C++ or MEX

The first step in the code generation process is to prepare the MATLAB algorithms by introducing implementation details and ensuring the code is using the subset of the MATLAB language that is supported for code generation. This subset includes basic operators, numerical computations, standard programming constructs and hundreds of built-in functions.

Implementation details are required to prepare MATLAB code for code generation because MATLAB is polymorphic - the behaviour of its operators and functions adapts to the nature of the input arguments they are operating on.

A result that can be achieved with a few lines of MATLAB may require tens or hundreds of lines of C code. For example, a simple function that multiplies two inputs of any size and data type is a single line of MATLAB code. When coding this in C, the engineer must take into account the size and data types of the inputs as well as whether they are real or complex. This is illustrated in the figure below.

coding in MATLAB

Polymorphism is one reason that MATLAB is a versatile and convenient language for exploring design ideas. When writing C code by hand or generating it with MATLAB Coder, however, engineers must explicitly specify the input sizes and data types for their algorithms. In MATLAB Coder, this can be done through the command line interface or the project UI as shown below.

MATLAB Coder

define type

For the same reason, certain local variables within the algorithm code in MATLAB have to be pre-allocated so the code generation engine knows the sizes and the data types of the variables to be used in the generated code.

Another key step in the preparation process is to check if the MATLAB algorithm code uses only those language features and constructs that support code generation. The product documentation lists all supported functions and language features.

In the traditional workflow, verifying that the handwritten C/C++ code functionally matches the original MATLAB algorithms is an important and challenging task.

Two common approaches are used to perform this functional verification:

  • Maintain separate file-based test benches and compare the test results for the MATLAB and C implementations;
  • Integrate the handwritten C code using the MEX API specification so that it may be directly called from within MATLAB and use test benches in MATLAB to exercise the MEX function and verify its result.

While the latter approach is more efficient and streamlined, the task of writing a MEX wrapper function that passes data between MATLAB and the C code can be tedious and error-prone. If care is not taken to allocate memory properly and perform proper error checking in the MEX wrapper code, then memory integrity violations can occur during the MEX function execution in MATLAB, potentially causing unpredictable results or a crash.

With the automated workflow, the MEX function can be automatically generated from the MATLAB algorithm that has been prepared for code generation. Engineers can use this step to determine if the modifications they made to the MATLAB code in preparation for code generation were sufficient.

Once the MEX function is successfully generated (indicating the preparation step was successful), it can be used to catch any potential design issues that might show up in the compiled code, such as unauthorised memory access or numerical inaccuracies introduced by the C/C++ compiler.

This functional verification step confirms that the MATLAB code is finally ready for C source code generation.

Because the automatically generated MEX functions are compiled versions of MATLAB algorithms, in some cases they may execute faster in MATLAB than the original algorithms, depending on the nature of the algorithms implemented.

After functionally verifying that the MEX functions are equivalent to their source MATLAB algorithms, engineers can turn off memory integrity checks and other options that may slow execution and then regenerate MEX functions that are further optimised for performance.

These functions can then be used in place of the original MATLAB algorithms to accelerate execution.

At this point, engineers may also generate C source code (as .c, .cpp, and .h files) that can then be compiled into a library or a stand-alone executable or integrated into other development projects written in C/C++. The code produced by MATLAB Coder is commented and readable, so that it can be readily understood.

The generated code can be optimised by modifying the MATLAB source code or by adjusting code generation settings that effect readability or performance.

Automatically generating readable and portable C code from MATLAB algorithms is an easy and efficient way to speed up the system design to implementation workflow. Preparation of the code requires introducing implementation requirements, pre-allocating variables and using the supported subset of the MATLAB language.

After assessing the generated C code, MATLAB algorithms can be refined and code can be regenerated in minutes. The results of the compiled code can be verified against the original golden reference MATLAB code. This quick iteration cycle enables engineers to converge on the desired C implementation while letting them work in MATLAB longer.

The result is a sharper focus on more efficient and optimised algorithm creation and less time spent on programming details in a lower level language.

Related Articles

Ricoh chooses u-blox module for long-lasting GNSS performance

The Ricoh Theta X camera incorporates the ZOE-M8B GNSS module from u-blox, allowing users to...

Single-step 3D printing method to create tiny robots

The breakthrough enables the mechanical and electronic systems needed to operate a robot to be...

Fast inspection technique for modern semiconductor devices

Researchers developed a novel approach to inspect and measure critical dimensions of...


  • All content Copyright © 2024 Westwick-Farrow Pty Ltd