Exploration of design ideas is the foundation of any design workflow. It helps create compelling products with unique value propositions that separate them from competition. For engineers, idea exploration takes the form of prototyping and testing algorithm variations to evaluate their behavioral 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
The speed with which an engineer can design and assess algorithm variations is critical to efficient optimization of the design. The high level interpreted language of MATLAB is a natural choice for engineers to express their ideas during design exploration, because it lets them focus on algorithm behavior 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.
Why translate MATLAB to C/C++?
Often engineers translate MATLAB algorithms to C/C++ code to create
standalone 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 instantaneously) from MATLAB speeds design exploration and product development iterations.
Why is manual conversion of MATLAB to C difficult?
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 behavior 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
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.
Benefits of Automatic Translation
Automating translation of MATLAB code to C code overcomes most, if not
all, of the problems associated with manual translation. Automatic MATLAB-to-C code generation offers the following 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. Design iterations become easier because engineers continue to use the interactive debugging and visualization capabilities in MATLAB throughout the process. The significant cost of producing and verifying hand-written C code can be eliminated for common design workflow uses such as prototyping algorithms as standalone executables, integrating algorithms as reusable 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 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 implementationsIntegrate 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
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.
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.