datasheets.com EBN.com EDN.com EETimes.com Embedded.com PlanetAnalog.com TechOnline.com
Events
UBM Tech
UBM Tech

Design Article

# Automatically generate C code

## 8/8/2011 4:07 PM EDT

Three-Step Workflow
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 math 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 tradeoffs between reducing memory footprint and  improving processor utilization 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.

Preparing Code: Introducing Implementation Details

The first step in the code generation process is to prepare your MATLAB algorithms by introducing implementation details and ensuring your 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 behavior of its operators and functions adapts to the nature of the input arguments they are operating upon.

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.

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.

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.

Test and Verify

In the traditional workflow, verifying that the hand-written C/C++ code functionally matches the original MATLAB algorithms is a very 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 hand-written 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 (as described in the previous section) 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 unauthorized 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.

Generate MEX Functions or C Code
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 optimized 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 standalone 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 optimized by modifying the MATLAB source code or by adjusting code generation settings that effect readability or performance.

Summary
Automatically generating readable and portable C code from your 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 optimized algorithm creation and less time spent on programming details in a lower level language.

• Head to the RF and Microwave Designline homepage for the latest updates in memory and storage.
• Sign up for the weekly RF and Microwave Designline Newsletter to be delivered to your mailbox with the latest highlights from the site.

agk

8/9/2011 9:27 AM EDT

A very convenient feature given by Matlab.This will save lot of efforts and time spend by the coding team. This will increase the out put of the design team. Many applications can be easily brought from Matlab into C .

t.alex

8/9/2011 12:06 PM EDT

This is really convenient tool for finetuning algorithms.

KB3001

8/9/2011 12:19 PM EDT

As systems get more and more complex, such approach is a must.

Charles.Desassure

8/10/2011 10:52 AM EDT

This is just another convenient tool or option that is available for engineers. The great thing is that it is always good to have options.

Robotics Developer

8/11/2011 10:14 AM EDT

What a neat idea! I will have to try it on my next project prototype effort. I wonder what the learning curve is like?

mfkinco

8/11/2011 12:23 PM EDT

In working with embedded software organizations, as complexity of systems and products grows, modeling and code generation is a necessity as one other reviewer noted. In addition, we find that linking model design elements to upstream requirements is critical as well as linking the requirements to downstream generated code, simulation and test. MATLAB and Simulink provide integration to leading tools such as PTC Integrity to do just this.

resistion

8/13/2011 8:54 AM EDT

Wow, very handy! Would have been nice a few years earlier, but better late than never!