You are on page 1of 7

Embedded MATLAB, part 1: From MATLAB to embedded C Houman Zarrinkoub, The MathWorks 5/18/2008 8:00 PM EDT Part 2 discusses

the process of integrating Embedded MATLAB code into Simulink models as part of a Model-Based Design workflow. Many embedded developers are familiar with the idea-to-implementation gap. Algorithm developers often create algorithm concepts in MATLAB due to its language features, extensive function libraries, and flexibility. As the design evolves toward embedded implementation, real-world constraints must be incorporated, which typically requires the user to manually translate MATLAB algorithms into C code. Manual translation involves rewriting the convenient MATLAB syntax for matrices into C implementations. The end result is multiple copies of the same algorithm written in different languages. At this stage, the user faces the burden of verifying that these copies remain equivalent throughout multiple design iterations. In this workflow the cost of verifying revisions quickly becomes prohibitive, resulting in a design that either solidifies too quickly or simply diverges from the original specification. Recently The MathWorks, creator of MATLAB, introduced new tools that directly address this issue. These tools can automatically convert a well-defined subset of MATLAB language, called Embedded MATLAB, into embeddable C code. This technology can reduce the development and verification cost of manual translation from MATLAB to C. The Embedded MATLAB language subset supports more than 270 MATLAB operators and functions and 90 Fixed-Point Toolbox functions. Working within the Embedded MATLAB subset, you can maintain one copy of the designone "truth"and elaborate it directly within MATLAB to incorporate embedded implementation requirements. Design iterations become easier because the Embedded MATLAB algorithm is still MATLAB code, and you retain the interactive debugging and visualization capabilities in MATLAB. This approach provides the algorithm domain expert and the embedded software engineer a common language and shared understanding of the design intent. You can automatically generate C code from the Embedded MATLAB code, eliminating the cost of producing and verifying hand-written C code. In this article, we first review features of MATLAB that are useful at the early stages of the design process. We then examine the inefficiencies associated with manually translating MATLAB "concept" code into C code for implementation. We then present an alternative

workflow, where all the embedded elaborations to the algorithm are done in MATLAB instead of C. Using an example, we highlight the steps necessary to make an algorithm compliant with the Embedded MATLAB subset and show the use of new tools that automatically translate an Embedded MATLAB code into embeddable C code. The table below compares MATLAB to C-code with respect to features relevant in the early phases of design.

(Click Table 1.

to

enlarge)

Converting a typical MATLAB algorithm into embeddable C code involves accommodating several implementation requirements:

Data Type ManagementData types must be determined before implementation. For example, the pixel values in image processing are often represented as 8-bit unsigned integers, and samples in speech processing are represented as 16-bit signed integers. The use of default 64bit double precision variables in MATLAB is not memory efficient.

Static Memory AllocationMATLAB seamlessly handles dynamically changing variable sizes at run time. In embedded applications, however, we usually avoid dynamic memory allocation and statically define memory for a given size and data type before using it.

Reduction of Computational Complexity and Memory FootprintEmbedded software designers spend a lot of time mapping high-level algorithms to operate efficiently within the limited memory and computational resources of the target hardware. This effort results in tuning the design to the instruction set and data representation of the target processor.

Fixed-Point SupportImplementation in embedded software or hardware may require that the algorithm be completely specified with fixed-point data types. Engineers typically perform these modifications by first translating the MATLAB algorithm into C code, which creates the design gap mentioned above. During this translation, the software engineer may introduce errors or numerical changes into the C code. If those changes are the intentional result of code optimizations, the algorithm designer may need to reproduce them in the MATLAB algorithm to maintain equivalence. This process adds unnecessary work and potential for errors. A workflow for embedded implementation based on Embedded MATLAB addresses these issues.

Unlike many MATLAB algorithms, Embedded MATLAB code is not an abstract mathematical representation of the design. It contains all the details needed for an efficient, embeddable C implementation. Any MATLAB code that complies with the Embedded MATLAB subset can generate embeddable C code. The process of ensuring compliance with the Embedded MATLAB subset involves the same four implementation requirements discussed previously. With Embedded MATLAB, the implementation constraints are specified directly in the MATLAB code. Applying the implementation requirements lets you:

Maintain one copy of your design in MATLAB Elaborate the design from a concept form to an implementation-ready form by incorporating embedded design constraints directly in MATLAB

Iterate, test, and debug the code using the visualization and analysis capabilities available in the MATLAB environment

Verify the functional correctness of the elaborated design Automatically generate embeddable C code using Real-Time Workshop Embedded MATLAB, part 1: From MATLAB to embedded C Houman Zarrinkoub, The MathWorks 5/18/2008 8:00 PM EDT Making a MATLAB algorithm compliant with the Embedded MATLAB subset may require you to:

Set data types for variablesYou assign data types either in the body of the MATLAB function or at compile time. Assignment at compile time is more convenient, since it permits a single MATLAB function to produce multiple C function variants with different data types, dimensions, and complexity. Because you specify data type and sizes of variables at the function interface, the data types and sizes of variables used in the body of the function are automatically inferred.

Accommodate array size changes without dynamic data allocationIn MATLAB, the size of a variable may change between loop iterations. You can accommodate array size changes for embedded implementations by using buffers of a constant maximum size and addressing subportions of the constant-size buffers.

Create an Embedded MATLAB compliant functionNot all MATLAB toolbox functions comply with the Embedded MATLAB subset. These functions are designed for flexibility and numerical accuracy, not for embedded implementation. You can use the toolbox function as a template or

reference to develop a functionally equivalent Embedded MATLAB function that meets the computational and memory constraints needed for efficient embedded C-code implementation. The desired C code can then be generated automatically from the Embedded MATLAB code.

Convert from floating-point to fixed-pointYou can use tools such as data logging and datatype override in the Fixed Point Toolbox to observe the dynamic ranges of variables in your MATLAB algorithm. These tools help you convert the algorithm to an optimized fixed-point representation in MATLAB. Because the original and the converted algorithms are both in MATLAB, you can directly compare the floating- and fixed-point results to ensure that the differences are within acceptable tolerance levels. Embedded MATLAB example

Let's use an example to illustrate the steps of this development process:

Elaborate the concept code to add embedded constraints by ensuring that it is Embedded MATLAB compliant and functionally equivalent to the reference code.

Automatically generate C code directly from the MATLAB desktop. An Embedded MATLAB workflow can be applied to a wide range of engineering problems in control design, communications, and signal and image processing. For this example, we chose an image processing algorithm known as adaptive median filtering because it deals with changing variable sizes, a typical scenario in many MATLAB programs. The MATLAB function shown in Figure 1, "adaptive_stats.m," extracts successively larger regions around a given element of a matrix to compute statistics (minimum, maximum, and median) over these regions. The function outputs a filtered center element of the matrix based on these statistics.

Figure 1. Noncompliant statistics function. Step 1: Verifying compliance with an Embedded MATLAB subset

To determine whether this function is compliant with the Embedded MATLAB subset, we recommend using the EMLMEX command. As it compiles the Embedded MATLAB code, EMLMEX checks for all potential Embedded MATLAB syntax violations and automatically generates a compilation report that describes the violations and provides links to problematic lines of code. The syntax of EMLMEX as applied to this function is:

The "example" option (following the eg delimiter) with EMLMEX provides an intuitive way to perform compile-time assignment. Recall the compliance task mentioned earlier of setting data types for variables: the -eg option sets the data types of variables in the Embedded MATLAB function by specifying an example for the function interface. EMLMEX extracts the data types and sizes of the variables in the MATLAB workspace listed in the cell array following the eg option. It assigns them at compile time to the inputs of the function, and then infers the data types and sizes of all variables in the function. The compilation report in Figure 1 shows that the original function is not compliant, since five variables (window_ind, region, rmin, rmax, rmed) change size as the variable s takes on different values in the loop. (The non-compliant portion is highlighted.) Recall the second compliance task mentioned earlier of accommodating array size changes without dynamic data allocation: translating this function to C manually would have resulted in undesirable dynamic memory allocations for those five variables. The solution is to introduce a new function that operates on the regions of interest of a constant maximum-size matrix. The modified function "adaptive_stats_roi.m," as shown in Figure 2, is identical to the original function except that it contains no size-change violations and has a call to the new function "roi_stats.m," which implements the new region-of-interest function. The new function call is highlighted in Figure 2.

Figure 2. Compliant function. Note that we included some implementation-oriented optimizations into the MATLAB code as we wrote the new function "roi_stats.m," by:

removing overhead of multiple function calls reducing computational complexity by removing redundant for-loops for each statistic obtaining three statistics by indexing different elements of the same sorted array Many MATLAB constructs, operators, and functions in our example are supported as part of the Embedded MATLAB subset. The "mysort" MATLAB function below sorts a sub-portion of an array.

By running the EMLMEX command and observing no error messages, we ascertain that the updated function "adaptive_stats_roi.m" is now Embedded MATLAB compliant and ready for automatic C code generation. Note that you can also use the MATLAB M-Lint checker to identify the compliance issues of your algorithm. Step 2: Automatic C-code generation from an Embedded MATLAB compliant function EMLC is a command-line tool that automatically translates compliant MATLAB code into C source code. You can use the following command to generate code for the compliant function "adaptive_stats_roi.m":

The report option lets you create an HTML report with hyperlinks to C source files and header files automatically generated from the MATLAB function.

(Click to enlarge) You can easily integrate existing C code within the Embedded MATLAB workflow. You may have developed a library of C functions and want to reuse them within your program. Embedded MATLAB provides C interface functions like "eml.ceval", which enable you to call external C functions from within Embedded MATLAB functions. For example, in our MATLAB function "roi_stats.m", we can replace the call to MATLAB function "mysort" with a call to an existing C function "c_sort" declared as:

This replacement involves the use of "eml.ceval" below, which passes input and output arguments to C functions by value or reference.

Summary Code generation using the Embedded MATLAB language subset aims to close the idea-toimplementation gap. It introduces a new workflow where algorithm design and elaboration occur in a single language and environment. Through automatic C-code generation from MATLAB, you maintain a single source for your design, tracking of iterations becomes easier, and algorithm designers and software engineers can work more collaboratively to quickly produce the best implementation. (To learn more about Embedded MATLAB, visit the Embedded MATLAB page on the MathWorks web site atwww.mathworks.com/products/featured/embeddedmatlab/.

This page contains demos, customer testimonials, technical details, and links to related MathWorks products. To learn how to use Embedded MATLAB through a detailed demonstration, watch one of the Webinars featuring Embedded MATLAB, such as "Algorithm Design and Code Generation with Embedded MATLAB"

at www.mathworks.com/company/events/archived_webinars.html. Also visit MATLAB CENTRAL www.mathworks.com/matlabcentral and search by keyword "Embedded MATLAB" to see user-contributed examples featuring Embedded MATLAB along with the MATLAB files used for demonstrations of the Webinar.) Part 2 discusses the process of integrating Embedded MATLAB code into Simulink models as part of a Model-Based Design workflow. About the author

Dr. Houman Zarrinkoub joined The MathWorks in 2001 as the senior team leader of the Signal Processing Applications team responsible for the Video and Image Processing Blockset. He is currently the Signal Processing Product Marketing Manager, responsible for signal processing toolboxes. Prior to joining The MathWorks, he spent 6 years at Nortel Networks as a wireless speech processing software engineer. He holds a BSEE from the McGill University in 1994, and MSEE and a PhD from the Institut Nationale de la Recherche Scientifique, Universite du Quebec in Canada. Related articles

Product: MathWorks rolls MATLAB C generator Product: MATLAB-to-C tool get major upgrade Blog: MATLAB to C showdown

You might also like