技术文章和时事通讯

the joy of generating c code from matlab -凯发k8网页登录

by bill chou, mathworks


engineers have translated low-level languages like c into machine code for decades using compilers. but is it possible to translate a high-level language like matlab® to c using coders? most engineers would agree that it’s possible in theory—but does it work in practice? is the generated code readable or spaghetti? efficient or bloated? fast or slow? and does it support industrial workflows, or just r&d?

this article addresses these concerns head-on. it provides tips and best practices for working with matlab coder™, as well as industry examples of successful applications of generated code by companies such as delphi, baker hughes, isonea, and dorsavi.

the code samples in this article are available for

comparing matlab and c code: a multiplication example

the simple matlab function below multiplies two inputs.

given scalar inputs, matlab coder generates the following c code:

as you can see, the generated code maps clearly back to the matlab code.

the same piece of matlab code, when given two matrix inputs, generates three nested for-loops in c:

recommended three-step iterative workflow

the simple function shown above can be implemented in a single step. but for more substantial projects, we recommend a structured approach using a three-step iterative workflow (figure 1):

  1. prepare your algorithm for code generation. examine and modify the matlab code to introduce implementation considerations needed for low-level c code, and use the matlab language and functions that support code generation.
  2. test the matlab code’s readiness for code generation using default settings. check for run-time errors by generating and executing a mex file. if successful, move to the next step. if not, repeat step 1 until you can generate a mex function.
  3. generate c code or keep the mex function from step 2. you can iterate on the matlab code to optimize either the generated c code (for look and feel, memory, and speed) or the mex function (for performance).
figure 1. three-step iterative workflow for generating code.

the matlab coder app guides you through this iterative process while enabling you to stay within the matlab environment. it analyzes your matlab code to propose data types and sizes for your inputs. it tests whether your matlab code is ready for code generation by generating a mex function, then executes the mex function to check for run-time errors (figure 2). equivalent command-line functions provide the same functionality so you can generate code as part of a script or function.

figure 2. left: automated checks for features and functions not supported for code generation. right: automated analysis and proposal for input data types and sizes.

the video below illustrates these steps with an example of generating a kalman filter to predict the trajectory of a bouncing ball. you’ll see that the three-step iterative process enables us to generate code that closely matches the original matlab results and satisfies its tracking requirements.

implementation constraints

as you prepare your matlab algorithm for code generation, you need to take account of implementation constraints resulting from the differences between matlab and c code. these include:

  • memory allocation. in matlab, memory allocation is automatic. in c code, memory allocation is manual—it is allocated either statically (using static), dynamically (using malloc), or on the stack (using local variables).
  • array-based language. matlab provides a rich set of array operations that allow concise coding of numerical algorithms. c code requires explicit for-loops to express the same algorithms.
  • dynamic typing. matlab automatically determines the data types and sizes as your code runs. c requires explicit type declarations on all variables and functions.
  • polymorphism. matlab functions can support many different input types, while c requires fixed type declarations. at the top level, you must specify the intended c function declaration.

let’s take a closer look at polymorphism. polymorphism can give a single line of matlab code different meanings depending on your inputs. for example, the function shown in figure 3 could mean scalar multiplication, dot product, or matrix multiplication. in addition, your inputs could be of different data types (logical, integer, floating-point, fixed-point), and they could be real or complex numbers.

figure 3. polymorphism example.

matlab is a powerful algorithm development environment precisely because you don’t need to worry about implementation details as you create algorithms. however, for the equivalent c code, you have to specify what operations mean. for example, the line of matlab code shown above could be translated into this single line of c code that returns b*c:

or, it could be translated into 11 lines of c code with 3 for-loops that multiply two matrices:

the video below uses a newton-raphson algorithm to illustrate the concept of taking implementation constraints into account. you’ll see that code generated using the three-step iterative workflow exactly matches the original matlab results.

working with the generated code: four use cases

once you have generated readable and portable c/c code from matlab algorithms using matlab coder, you have several options for using it. for example, you can:

industry success stories

  • generated a dll from sequence prediction algorithms and integrated it into surface decoding software running on a pc that enables downhole data to be decoded quickly and reliably during drilling operations.
  • generated c code from motion analysis algorithms and compiled it into a dll, which was then integrated into their c# application running on a pc that analyzes the athlete’s movements to diagnose injury.

  • generated fixed-point c code from heart rhythm monitoring algorithms and compiled it for an arm cortex-m processor.
  • generated c code for an automotive radar sensor alignment algorithm and compiled it for an arm10 processor.
  • generated c code from acoustic respiratory monitoring algorithms and compiled it for an iphone app, an android app, and cloud-based server software.

multicore-capable code generation and other optimization methods

in matlab, for-loops whose iterations are independent of each other can be run in parallel simply by replacing for with parfor. matlab coder uses the open multiprocessing (openmp) application interface to support shared-memory, multicore code generation from parfor loops. openmp is supported by many c compilers (for example, microsoft® visual studio® professional).

you can use matlab coder with embedded coder® to further optimize code efficiency and customize the generated code. embedded coder provides optimizations for fine-grained control of the generated code’s functions, files, and data. for example, you can use to control the declaration and definition of a global variable in the generated code, and use to customize banners and comments in the generated code. embedded coder also improves code efficiency by using code replacement libraries, which replace certain operators and functions with implementations optimized for popular processors like and .

testing the generated code

as you develop your matlab algorithm, you can create unit tests to verify that the algorithm produces the results you expect. tests written using the matlab unit testing framework can be reused to verify that the generated code behaves the same way as your matlab algorithm. the videos below show how you can reuse the unit tests in embedded coder in combination with software-in-the-loop (sil) and processor-in-the-loop (pil) tests on the generated standalone code or library (figure 4).

an automated workflow

matlab coder enables an automated workflow for translating matlab algorithms into c code. with this workflow you spend less time writing and debugging low-level c code and more time developing, testing, and tuning designs. by maintaining one golden reference in matlab, including the algorithm and test benches, you can propagate algorithmic changes to your c code more quickly. automated tools like the matlab unit testing framework and the embedded coder sil and pil testing framework let you test both the matlab code and the c code thoroughly and systematically. whether you are implementing designs running on , , , or , matlab coder will help you get from matlab to c code faster and with fewer manual translation errors.

published 2016 - 92987v00

view articles for related capabilities

网站地图