Generate Fixed-Point C Code
Note
To generate fixed-point code from MATLAB® you must have both the Fixed-Point Designer™ product and the MATLAB Coder™ product. You also must have a C compiler.
This example shows how to generate code for a simple function that multiplies and accumulates two input values. This is the type of code that you could embed in external hardware. The function is
function acc = mult_acc(x,a,acc)
acc = accumpos(acc,x*a);
This code defines the test bench inputs, sets up the required code generation
properties, and generates the code. The test bench inputs are specified as fixed-point
numbers. The x input is a random number, a is 0.9,
and the accumulator, acc, is initialized to 0. The
coder.HardwareImplementation object specifies properties of the
external hardware that impact the generated code. The examples specifies a 40-bit
accumulator. The coder.CodeConfig object has properties that
directly affect code generation. The codegen command takes the
function, the configuration object as the input arguments and generates embeddable C
code.
x = fi(rand,true,16,15); a = fi(0.9,true,16,15); acc = fi(0,true,40,30); %% hi = coder.HardwareImplementation; hi. ProdHWDeviceType = 'Generic->Custom' hi. TargetHWDeviceType = 'Generic->Custom' hi.TargetBitPerLong = 40; hi.ProdBitPerLong = 40; hc = coder.config('lib'); hc.HardwareImplementation = hi; hc.GenerateReport = true; codegen mult_acc -config hc -args {x,a,acc}
The generated C code is:
/* Include Files */
#include "mult_acc.h"
/* Function Definitions */
/*
* Arguments : short x
* short a
* long *acc
* Return Type : void
*/
void mult_acc(short x, short a, long *acc)
{
*acc += x * a;
}Note
For a list of functions supported for code generation, see Functions and Objects Supported for C/C++ Code Generation.