2. MATLAB Coder Code Generation Quick Start Guide
-
Upload
shahbaz-ali-khan -
Category
Documents
-
view
377 -
download
0
Transcript of 2. MATLAB Coder Code Generation Quick Start Guide
![Page 1: 2. MATLAB Coder Code Generation Quick Start Guide](https://reader035.fdocuments.us/reader035/viewer/2022081717/5533400d5503467e208b4900/html5/thumbnails/1.jpg)
Feedback/Questions: email [email protected]
1
Generating C code with MATLAB Coder: a Quick Start Guide (R2012a)
MATLAB Coder lets you generate C code from your MATLAB code. You can
generate stand-alone ANSI-C code or C code that includes the necessary
interfaces to run within MATLAB as compiled MEX file. This quick start
guide focuses on how to generate stand-alone ANSI-C code. Refer to
“Preparing MATLAB Code for MATLAB Coder: a Quick Start Guide” [1] for
information about how to make your MATLAB code compliant.
Steps to Generating Stand-Alone C Code When you generate stand-alone C code, the first step is always to generate
a MEX file and check that it runs correctly in MATLAB before generating
the stand-alone C code. The MEX file includes checks that make detecting
and correcting a run-time error much easier. Refer to [1] for more detail.
Generate a MEX file and verify behavior [1]
Generate the initial stand-alone C code
Understand the generated C code in an external C project
Customize the generated C code
Integrate the generated C code
Generating the Initial Stand-Alone C Code To generate stand-alone C Code, switch to the “Build” pane in MATLAB
Coder and select “C/C++ Static Library”, “C/C++ Dynamic Library” or “C/C++
Executable”.
What’s the difference between Static/Dynamic Library and
Executable?
As far as the generated C code is concerned, there is no difference.
Static (resp. Dynamic) Library
MATLAB Coder builds a static (resp. dynamic) library, which you can link against in a C-based project. Location: codegen/lib/<topLevelName> (resp. dll)
Executable You must provide a main function. MATLAB Coder then builds an executable file that calls the generated code. Location: codegen/exe/<topLevelName>
Understand the Generated C Code
Comments
It is often helpful to add the original MATLAB Code as a comment in the C
code to more easily understand where the C code is coming from.
Under More Settings-> Code Appearance:
![Page 2: 2. MATLAB Coder Code Generation Quick Start Guide](https://reader035.fdocuments.us/reader035/viewer/2022081717/5533400d5503467e208b4900/html5/thumbnails/2.jpg)
Feedback/Questions: email [email protected]
2
Memory Allocation
MATLAB Coder distinguishes between 3 types or arrays:
Fixed-size arrays such as 12 by 3
MATLAB Coder always allocates memory on the stack – or as static is there is no room on the stack
Unknown size arrays with known maximum size (‘max-size arrays’)
If your code does not include any truly unknown size array, you can select to never use dynamic memory allocation, use if for all variable-size arrays or only for those that are larger than a given size: under “More Settings” -> Memory (see below)
Truly unknown size arrays (no known maximum size)
Memory allocation for truly unknown size arrays always happens at run time (dynamic memory allocation via emxEnsureCapacity calls)
Customize the C Code You can obtain more efficient C code by following those best practices:
Ensure that all arrays have a maximum size (if appropriate)
Add information about array sizes where needed. For example:
assert(N < 25); y = zeros(1,N);
See also “Optimize indexing” below for another practice that may help.
Ensure that the generated code passes arguments by reference
C always passes arrays by reference. Depending on the context, MATLAB
Coder may have to make a local copy of the variable before passing it to a
sub-function.
Tip: use in-place syntax “a = foo(a)” both at the calling site and at
function declaration to avoid a necessary local copy
x = foo(x,b) … function a = foo(a,b) ….
y = foo(x,b) … function a = foo(a,b) ….
The input and output names are the same both at the call site and the function declaration. MATLAB Coder does not need to make a local copy of ‘x’ and truly passes it by reference
The call site uses two different names for the input and output variables. Hence, variables ‘x’ and ‘y’ both exist after the call to ‘foo’: MATLAB Coder must duplicate the memory
Use logical array indexing sparingly
Logical array indexing is the ability to perform operations on sub-elements
of an array based on a logical index. For example: you can clip all elements
larger than 255 with:
x(x>255) = 255;
Rewriting it as follows generally yields better code:
for ii=1:numel(x), if (x(ii)>255), x(ii) = 255; end, end
Optimize indexing
MATLAB Coder may not be able to recognize that (i:i+9) has a fixed length
of 10. Rewrite it as “i + (0:9)” to give the necessary hint to MATLAB Coder.
Enforce scalar typing
![Page 3: 2. MATLAB Coder Code Generation Quick Start Guide](https://reader035.fdocuments.us/reader035/viewer/2022081717/5533400d5503467e208b4900/html5/thumbnails/3.jpg)
Feedback/Questions: email [email protected]
3
There are cases where MATLAB Coder cannot know that ‘x’ is a scalar. For example, you know that ‘a’ always has at least one positive element. So, x = find(a>0, 1,'first') is scalar but MATLAB Coder types it as ‘:1’ because it can’t know that it won’t be empty
Enforce scalar typing by modifying the line to:
x = find(a>0, 1,'first'); x = x(1);
Integrate the Code in an External C Project
Files to Use
Get all the .c and .h files from the target directory (static lib example:
codegen/lib/<topLevelName>). They represent all the files needed to
proceed in most cases.
Memory Layout MATLAB is column-major: consecutive elements in a 2D matrix correspond
to elements in a column. On the other hand, C is row-major.
The C code that MATLAB Coder generates mimics the MATLAB behavior.
Consequently, if any of the input (resp. output) arguments is a multi-
dimensional (2D or more) matrix, you may need to transpose your input
(resp. output) to match an external C testbench.
Argument Types
Input and output arguments map to the following C function arguments
Fixed-size arrays Pointer to array: x[10]
Max-size array - not dynamic
Pointer to array along with array with actual runtime sizes: x_data[10] and x_sizes[2]
Dynamically allocated arrays
“emxArrays”, which are special types defined in a .h file produced. MATLAB Coder provides helper functions to create and destroy those arrays. Refer
to the “Atoms” demo in the documention at: MATLAB Coder -> Demos -> Generating C Code from MATLAB Code -> “Atoms” Simulation for more detail
FAQs Do I need Embedded Coder?
Embedded Coder lets you customize the C code generated for a stand-
alone target. The main advantages to Embedded Coder are the ability to:
- Target Code Replacement Libraries (CRL) for embedded targets
- Generate code for specific targets (e.g. TI DSP) and co-simulate
with IDEs
- Generate reentrant code
- Customize the code style such as defining name rules for variables
File I/O Support
MATLAB Coder does not directly support ‘load’ or ‘fopen’.
While there is limited direct support for file I/O (Video and Audio file
reader system objects), you can find an example of how to read from and
write to generic files by looking at the example for “coder.opaque”
Command-line equivalent
You can generate code and set all options from the command line. See
“codegen” and “coder.config”
Clashing function names when generating code for multiple functions
If you generate code independently for several functions, MATLAB Coder
may generate C functions that have the same name but different behavior
for some of the sub-functions. When you try to merge the files for all
functions into one directory, this may lead to a conflict.
![Page 4: 2. MATLAB Coder Code Generation Quick Start Guide](https://reader035.fdocuments.us/reader035/viewer/2022081717/5533400d5503467e208b4900/html5/thumbnails/4.jpg)
Feedback/Questions: email [email protected]
4
Solution: If you generate code simultaneously for several
functions, MATLAB Coder generates C code with the awareness of
all other parts of your design and avoids name clashes. Simply use
the “multiple entry-point files” capability, which is to define
several top-level functions to the project:
Using Target-Specific Libraries
MATLAB Coder lets you replace operators and functions with target-
specific implementations. This capability is described in the documentation
under the heading Code Replacement Library (CRL) and requires
Embedded Coder.
Generating re-entrant / thread-safe code?
This capability requires Embedded Coder. Under More Settings -> Memory
Generating C++ code?
MATLAB Coder always generates C code. When you select the C++ option,
MATLAB Coder generates C code (with a .cpp extension) that a C++
compiler can compile. Select C++ under More Settings -> General ->
Language
Useful Functions Refer to the documentation for details
coder.ceval Call an external C function, which you already have, from the generated C code
coder.cstructname Specify the name of the C structure generated for your MATLAB structure
coder.inline Enforce of prevent inlining of sub-functions. When you use coder.inline(‘always’) in a MATLAB sub-function, the corresponding code is inlined in the generated C code
coder.target Reserved variable, which is ‘empty’ when running the MATLAB interpreter. Lets you define different processing in code generation and MATLAB mode: if isempty(coder.target) % This happens in MATLAB else % This happens in code generation end
coder.nullcopy Suppresses the initialization statement for a variable defined as “zeros”. This results in slightly faster code, but you must ensure that all slices of the variable are written to before read from
coder.config Create a configuration object to set all the necessary options when generating C code from the command line with the “codegen” command