Generating Modular Code for Functions

This example shows how to generate modular HDL code from MATLAB® code containing functions.


HDL Coder™ by default inlines the body of all MATLAB functions called in the top level design and generates HDL code in a single file. However turning on the advanced coding option 'Generate instantiable code for functions' helps you generate module code in multiple files.


The MATLAB design used in the example is an implementation of an LMS filter. The LMS filter is used to identify an FIR filter signal embedded in the noise.

design_name = 'mlhdlc_lms_fcn';
testbench_name = 'mlhdlc_lms_fir_id_tb';

Let us take a look at the MATLAB design

% MATLAB Design: Adaptive Noise Canceler algorithm using Least Mean Square 
% (LMS) filter implemented in MATLAB
% Key Design pattern covered in this example: 
% (1) Use of function calls
% (2) Function inlining vs instantiation knobs available in the coder
% (3) Use of system objects in the testbench to stream test vectors into the design


function [filtered_signal, y, fc] = mlhdlc_lms_fcn(input, desired, step_size, reset_weights)
% 'input'  : The signal from Exterior Mic which records the ambient noise.
% 'desired': The signal from Pilot's Mic which includes 
%            original music signal and the noise signal
% 'err_sig': The difference between the 'desired' and the filtered 'input'
%            It represents the estimated music signal (output of this block)
% The LMS filter is trying to retrieve the original music signal ('err_sig') 
% from Pilot's Mic by filtering the Exterior Mic's signal and using it to 
% cancel the noise in Pilot's Mic. The coefficients/weights of the filter 
% are updated(adapted) in real-time based on 'input' and 'err_sig'.

% register filter coefficients
persistent filter_coeff;
if isempty(filter_coeff)
    filter_coeff = zeros(1, 40);

% Variable Filter
% call 'tapped_delay_fcn' function on path to create 40-step tapped delay
delayed_signal = mtapped_delay_fcn(input);

% apply filter coefficients 
weight_applied = delayed_signal .* filter_coeff;

% call 'treesum' function on matlab path to sum up the results
filtered_signal = mtreesum_fcn(weight_applied);

% Output estimated Original Signal
td = desired;
tf = filtered_signal;

esig = td - tf;
y = esig;

% Update Weights
% call 'update_weight_fcn' function on matlab path to 
% calculate the new weights
updated_weight = update_weight_fcn(step_size, esig, delayed_signal, ...
                                   filter_coeff, reset_weights);

% update filter coefficients register
filter_coeff = updated_weight;

fc = filter_coeff;

function y = mtreesum_fcn(u)
%Implement the 'sum' function without a for-loop
%  y = sum(u);

%  The loop based implementation of 'sum' function is not ideal for 
%  HDL generation and results in a longer critical path. 
%  A tree is more efficient as it results in
%  delay of log2(N) instead of a delay of N delay

%  This implementation shows how to explicitly implement the vector sum in 
%  a tree shape to enable hardware optimizations.

%  The ideal way to code this generically for any length of 'u' is to use 
%  recursion but it is not currently supported by MATLAB Coder

% NOTE: To instruct MATLAB Coder to compile an external function, 
% add the following compilation directive or pragma to the function code

% This implementation is hardwired for a 40tap filter.

level1 = vsum(u);
level2 = vsum(level1);
level3 = vsum(level2);
level4 = vsum(level3);
level5 = vsum(level4);
level6 = vsum(level5);
y = level6;

function output = vsum(input)


vt = input(1:2:end);
for i = int32(1:numel(input)/2)
    k = int32(i*2);
    vt(i) = vt(i) + input(k);

output = vt;

function tap_delay = mtapped_delay_fcn(input)
% The Tapped Delay function delays its input by the specified number 
% of sample periods, and outputs all the delayed versions in a vector
% form. The output includes current input

% NOTE: To instruct MATLAB Coder to compile an external function, 
% add the following compilation directive or pragma to the function code

persistent u_d;
if isempty(u_d)
    u_d = zeros(1,40);

u_d = [u_d(2:40), input];

tap_delay = u_d;

function weights = update_weight_fcn(step_size, err_sig, delayed_signal, filter_coeff, reset_weights)
% This function updates the adaptive filter weights based on LMS algorithm

%   Copyright 2007-2010 The MathWorks, Inc.

% NOTE: To instruct MATLAB Coder to compile an external function, 
% add the following compilation directive or pragma to the function code

step_sig = step_size .* err_sig;
correction_factor = delayed_signal .* step_sig;
updated_weight = correction_factor + filter_coeff;

if reset_weights
    weights = zeros(1,40);
    weights = updated_weight;
clear ('mlhdlc_lms_fcn');
% returns an adaptive FIR filter System object,
% HLMS, that computes the filtered output, filter error and the filter
% weights for a given input and desired signal using the Least Mean
% Squares (LMS) algorithm.

stepSize = 0.01;
reset_weights =false;

hfilt = dsp.FIRFilter;          % System to be identified
hfilt.Numerator = fir1(10, .25);

rng('default'); % always default to known state  
x = randn(1000,1);                         % input signal
d = step(hfilt, x) + 0.01*randn(1000,1);    % desired signal

hSrc = dsp.SignalSource(x);
hDesiredSrc = dsp.SignalSource(d);

hOut = dsp.SignalSink;
hErr = dsp.SignalSink;
%Call to the design
while (~isDone(hSrc))
    [y, e, w] = mlhdlc_lms_fcn(step(hSrc), step(hDesiredSrc), stepSize, reset_weights);
    step(hOut, y);
    step(hErr, e);

figure('Name', [mfilename, '_plot']);
subplot(2,1,1), plot(1:1000, [d,hOut.Buffer,hErr.Buffer]);
title('System Identification of an FIR filter');
legend('Desired', 'Output', 'Error');
xlabel('time index'); ylabel('signal value');
subplot(2,1,2); stem([hfilt.Numerator.', w(end-10:end).']);
xlabel('coefficient #'); ylabel('coefficient value');

Create a New Folder and Copy Relevant Files

Execute the following lines of code to copy the necessary example files into a temporary folder.

mlhdlc_demo_dir = fullfile(matlabroot, 'toolbox', 'hdlcoder', 'hdlcoderdemos', 'matlabhdlcoderdemos');
mlhdlc_temp_dir = [tempdir 'mlhdlc_fcn_partition'];

% create a temporary folder and copy the MATLAB files.
[~, ~, ~] = rmdir(mlhdlc_temp_dir, 's');

copyfile(fullfile(mlhdlc_demo_dir, [design_name,'.m*']), mlhdlc_temp_dir);
copyfile(fullfile(mlhdlc_demo_dir, [testbench_name,'.m*']), mlhdlc_temp_dir);
% At the end of this step you should see the design files being copied to
% a temporary folder.

Simulate the Design

It is always a good practice to simulate the design with the testbench prior to code generation to make sure there are no runtime errors.


Create a New HDL Coder™ Project

coder -hdlcoder -new mlhdlc_fcn_partition

Next, add the file 'mlhdlc_lms_fcn.m' to the project as the MATLAB Function and 'mlhdlc_lms_fir_id_tb.m' as the MATLAB Test Bench.

You can refer to Getting Started with MATLAB to HDL Workflow tutorial for a more complete tutorial on creating and populating MATLAB HDL Coder projects.

Run Fixed-Point Conversion and HDL Code Generation

Launch the Workflow Advisor from the Build tab and right click on the 'Code Generation' step and choose the option 'Run to selected task' to run all the steps from the beginning through the HDL code generation.

Examine the generated HDL code by clicking on the hyperlinks in the Code Generation Log window. Notice that the HDL code for all the functions in the design is inlined into a single file 'mlhdlc_lms_fcn_FixPt.vhd'

Generate Instantiable Code

To generate modular code for all the functions in separate files please turn on this advanced coding option 'Generate instantiable code for functions'

Rerun Code Generation Step

Now reset the code generation task and rerun the HDL code generation step to see how code is generated in multiple files for the functions

Control Inlining Per Function

Sometimes it is preferable to inline code for helpers and utilities and instantiate them. To locally control inlining of such functions use the 'coder.inline' pragma in the MATLAB code.


Type the following command to see how to use coder.inline pragma

help coder.inline

Known Limitations

The following limitations exist when instantiating HDL code from functions.

  1. Function calls inside conditional expressions and for loops get inlined and do not get instantiated.

  2. Functions with states get inlined.

Clean up the Generated Files

You can run the following commands to clean up the temporary project folder.

mlhdlc_demo_dir = fullfile(matlabroot, 'toolbox', 'hdlcoder', 'hdlcoderdemos', 'matlabhdlcoderdemos');
mlhdlc_temp_dir = [tempdir 'mlhdlc_fcn_partition'];
clear mex;
cd (mlhdlc_demo_dir);
rmdir(mlhdlc_temp_dir, 's');
Was this topic helpful?