Main Content

Accelerate Fixed-Point Simulation

This example shows how to accelerate fixed-point algorithms using the fiaccel function. Code acceleration provides optimizations for accelerating fixed-point algorithms through MEX file generation. Fixed-Point Designer™ provides a convenience function fiaccel to convert your MATLAB® code to a MEX function, which can greatly accelerate the execution speed of your fixed-point algorithms. In this example, you generate a MEX function from MATLAB code, run the generated MEX function, and compare the execution speed with MATLAB code simulation.

Description of the Example

This example uses a first-order feedback loop. Casting to the output-signal type prevents infinite bit growth. The output signal is delayed by one sample and fed back to dampen the input signal.

Inspect the MATLAB Feedback Function Code

The MATLAB function that performs the feedback loop is in the file fiaccelFeedback.m. Subscripted assignment into the output y casts to y's type and prevents infinite bit growth.

function [y,z] = fiaccelFeedback(x,a,y,z)
    for n = 1:length(x)
        y(n) = x(n) - a*z;
        z(:) = y(n);
    end
end

The following variables are used in this function:

  • x is the input signal vector.

  • y is the output signal vector.

  • a is the feedback gain.

  • z is the unit-delayed output signal.

Create the Input Signal and Initialize Variables

clearvars

Put the settings of the random number generator to its default value.

rng('default');

Input signal.

x = fi(2*rand(1000,1)-1,true,16,15);

Feedback gain.

a = fi(0.9,true,16,15);

Initialize output. Fraction length is chosen to prevent overflow.

y = fi(zeros(size(x)),true,16,12);

Initialize delayed output.

z = cast(0,'like',y);

Run Interpreted MATLAB and Time

tic
y1 = fiaccelFeedback(x,a,y,z);
t1 = toc;

Build the MEX Version of the Feedback Code

Declare feedback gain parameter a constant for code generation.

fiaccel fiaccelFeedback -args {x,coder.Constant(a),y,z} -o fiaccelFeedback_mex

Run the MEX Version and Time

Run once to load the MEX file in memory.

fiaccelFeedback_mex(x,a,y1,z);

Run again to time.

tic
y2 = fiaccelFeedback_mex(x,a,y,z);
t2 = toc;

Acceleration Ratio

Compare the MEX execution speed with MATLAB code simulation.

ratio_of_speed_up = t1/t2
ratio_of_speed_up =

  176.7198

Verify that Fixed-Point Interpreted MATLAB and MEX Outputs are Identical

isequal(y1,y2)
ans =

  logical

   1

Suppress Code Analyzer warnings.

%#ok<*NOPTS>

See Also