Beruflich Dokumente
Kultur Dokumente
Listing 4: In Matlab, you don’t need to think about memory allocation. Fixed-
and variable-size arrays in Matlab are shown.
Listing 5: Shown is a Matlab function that maps one integer to another via a
simple LUT.
we’ll identify two types of Matlab cate memory for your data. If the
arrays: fixed-size and variable-size. Matlab code uses a fixed-size array,
Fixed-size arrays are Matlab arrays the translation is a simple matter
for which the dimensions remain of allocating an equivalent array in
fixed during runtime. Variable-size C. Because the array size is known
arrays change in size or shape at compile time, you can allocate
during runtime. Some Matlab ex- the array statically or on the stack,
amples are shown in Listing 4. and there’s no need to resort to Listing 9: Shown is the C translation of findrand with fixed-size arrays.
Variable-size arrays are an ex- dynamic allocation. For example,
tremely useful feature of Matlab. the Matlab function in Listing 5 tion tool uses the size of the array location, you have several solutions
Most non-trivial Matlab programs maps one integer to another via a to determine whether to allocate for handling the variable-size array:
make use of them; sometimes simple look-up table (LUT), which the array on the stack, statically or • Rewrite the algorithm to elimi-
you simply don’t know how is a vector of fixed size. dynamically. However, you have nate all variable-size arrays—
large an array (such as an image The equivalent C code, with complete control over this behav- You can emulate variable-size
or resampled buffer) will be until LUT allocated on the stack, is ior and, for example, can direct arrays by pre-allocating a maxi-
runtime. Although the Matlab shown in Listing 6. Similarly, you the translator to avoid all dynamic mum, fixed-size array, then use
language doesn’t explicitly distin- can allocate LUT in static memory, memory allocation. extra “bookkeeping” variables
guish between fixed-size and vari- as shown in Listing 7. and logic to track the actual
able-size arrays, you’ll see that this A tool we developed for Variable-size arrays array size during runtime. This
distinction becomes critical when Matlab-to-C translation takes the If your Matlab code uses variable- method can be done in C or
translating to C. same approach to fixed-size ar- size arrays, how do you translate even Matlab, although this
rays. When the size of a Matlab them to C? The natural solution goes against the grain of nor-
Fixed-size arrays array is known ahead of time, it is to allocate an equivalent array mal Matlab coding style.
When translating Matlab code to simply allocates the equivalent dynamically. But in an environment • Use a custom memory alloca-
C, you must choose how to allo- array in C. By default, the transla- that prohibits dynamic memory al- tor in C such as a pool manag-