You are on page 1of 17

6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

Filter Audio Signal Using MATLAB Code


Learning Objectives
In this tutorial, you will learn how to:

• Use the MATLAB Function block to add MATLAB® functions to Simulink® models for modeling, simulation, and
deployment to embedded
processors.
This capability is useful for coding algorithms that are better stated in
the textual language of MATLAB than in the
graphical language of Simulink.
• Use coder.extrinsic to call MATLAB code from a MATLAB Function block.
This capability allows you to call existing MATLAB code from Simulink without first having to make this code suitable
for code
generation, allowing for rapid prototyping.
• Check that existing MATLAB code is suitable for code generation.
• Convert a MATLAB algorithm from batch processing to streaming.
• Use persistent variables in code that is suitable for code
generation.
You need to make the filter weights persistent so that the filter
algorithm does not reset their values each time it runs.

Tutorial Prerequisites
• What You Need to Know
• Required Products

What You Need to Know


To work through this tutorial, you should have basic familiarity with MATLAB software. You should also understand how to
create a basic Simulink model and how to simulate that model. For more information, see Create a Simple Model.

Required Products
To complete this tutorial, you must install the following products:

• MATLAB
• MATLAB
Coder™
• Simulink
• Simulink
Coder
• DSP System Toolbox™
• C compiler
For a list of supported compilers, see Supported Compilers.

For instructions on installing MathWorks® products, refer to the installation documentation. If you have
installed MATLAB
and want to check which other MathWorks products are installed, enter ver in the
MATLAB Command Window. For
instructions on installing and setting up a C
compiler, see Setting Up the C or C++ Compiler (MATLAB Coder).

Example: The LMS Filter


• Description
• Algorithm
• Filtering Process
• Reference

Description

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 1/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

A least mean squares (LMS) filter is an adaptive filter that adjusts its transfer
function according to an optimizing
algorithm. You provide the filter with an
example of the desired signal together with the input signal. The filter then
calculates the filter weights, or coefficients, that produce the least mean squares
of the error between the output signal and
the desired signal.

This example uses an LMS filter to remove the noise in a music recording. There
are two inputs. The first input is the
distorted signal: the music recording plus
the filtered noise. The second input is the desired signal: the unfiltered noise.
The
filter works to eliminate the difference between the output signal and the
desired signal and outputs the difference, which,
in this case, is the clean music
recording. When you start the simulation, you hear both the noise and the music.
Over time,
the adaptive filter removes the noise so you hear only the music.

Algorithm
This example uses the least mean squares (LMS) algorithm to remove noise from an
input signal. The LMS algorithm
computes the filtered output, filter error, and
filter weights given the distorted and desired signals.

At the start of the tutorial, the LMS algorithm uses a batch process to filter the
audio input. This algorithm is suitable for
MATLAB, where you are likely to load in the entire signal and process it all
at once. However, a batch process is not suitable
for processing a signal in real
time. As you work through the tutorial, you refine the design of the filter to
convert the
algorithm from batch-based to stream-based processing.

The baseline function signature for the algorithm


is:

function [ signal_out, err, weights ] = ...

lms_01(signal_in, desired)

The filtering is performed in the following


loop:

for n = 1:SignalLength

% Compute the output sample using convolution:

signal_out(n,ch) = weights' * signal_in(n:n+FilterLength-1,ch);

% Update the filter coefficients:

err(n,ch) = desired(n,ch) - signal_out(n,ch) ;

weights = weights + mu*err(n,ch)*signal_in(n:n+FilterLength-1,ch);

end

where SignalLength is the length of the input signal,


FilterLength is the filter length, and mu
is the adaptation step size.

 What Is the Adaptation Step Size?

Filtering Process
The filtering process has three phases:

• Convolution
The convolution for the filter is performed
in:
signal_out(n,ch) = weights' * signal_in(n:n+FilterLength-1,ch);

 What Is Convolution?
• Calculation of error
The error is the difference between the desired signal and the output
signal:
err(n,ch) = desired(n,ch) - signal_out(n,ch);

• Adaptation
The new value of the filter weights is the old value of the filter weights
plus a correction factor that is based on the error
signal, the distorted
signal, and the adaptation step
size:
weights = weights + mu*err(n,ch)*signal_in(n:n+FilterLength-1,ch);

Reference
Haykin, Simon. Adaptive Filter Theory. Upper Saddle River,
NJ: Prentice-Hall, Inc., 1996.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 2/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

Files for the Tutorial


• About the Tutorial Files
• Location of Files
• Names and Descriptions of Files

About the Tutorial Files


The tutorial uses the following files:

• Simulink model files for each step of the tutorial.


• MATLAB code files for each step of the example.
Throughout this tutorial, you work with Simulink models that call MATLAB files that contain a simple least mean
squares (LMS)
filter algorithm.

Location of Files
The tutorial files are available in the following folder:
docroot\toolbox\simulink\examples\lms. To run the tutorial,
you
must copy these files to a local folder. For instructions, see Copying Files Locally.

Names and Descriptions of Files

Type Name Description

MATLAB files lms_01 Baseline MATLAB implementation of batch filter. Not


suitable for code
generation.

lms_02 Filter modified from batch to streaming.

lms_03 Frame-based streaming filter with Reset and Adapt


controls.

lms_04 Frame-based streaming filter with Reset and Adapt


controls.
Suitable for code generation.

lms_05 Disabled inlining for code generation.

lms_06 Demonstrates use of coder.nullcopy.

Simulink model acoustic_environment Simulink model that provides an overview of the acoustic
files environment.

noise_cancel_00 Simulink model without a MATLAB Function block.

noise_cancel_01 Complete noise_cancel_00 model including a


MATLAB
Function block.

noise_cancel_02 Simulink model for use with


lms_02.m.

noise_cancel_03 Simulink model for use with


lms_03.m.

noise_cancel_04 Simulink model for use with


lms_04.m.

noise_cancel_05 Simulink model for use with


lms_05.m.

noise_cancel_06 Simulink model for use with


lms_06.m.

design_templates Simulink model containing Adapt and Reset controls.

Tutorial Steps
• Copying Files Locally
• Setting Up Your C Compiler
• Running the acoustic_environment Model
• Adding a MATLAB Function Block to Your Model
• Calling Your MATLAB Code As an Extrinsic Function for Rapid Prototyping
• Simulating the noise_cancel_01 Model
https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 3/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

• Modifying the Filter to Use Streaming


• Adding Adapt and Reset Controls
• Generating Code
• Optimizing the LMS Filter Algorithm

Copying Files Locally


Copy the tutorial files to a local folder:

1. Create a local solutions folder, for


example, c:\test\lms\solutions.
2. Change to the docroot\toolbox\simulink\examples
folder. At the MATLAB command line,
enter:
cd(fullfile(docroot, 'toolbox', 'simulink', 'examples'))

3. Copy the contents of the lms subfolder to your


solutions folder, specifying the full
path name of the solutions
folder:
copyfile('lms', 'solutions')

Your
solutions folder now contains a complete
set of solutions for the tutorial. If you do not want to perform the
steps for each task, you can view the supplied solution to see how the
code should look.
4. Create a local work folder, for example,
c:\test\lms\work.
5. Copy the following files from your
solutions folder to your
work folder.
• lms_01
• lms_02
• noise_cancel_00
• acoustic_environment
• design_templates

Your work folder now contains all the files


that you need to get started.
You are now ready to set up your C compiler.

Setting Up Your C Compiler


Building your MATLAB Function block requires a supported compiler.
MATLAB automatically selects one as the default
compiler. If you have
multiple MATLAB-supported compilers installed on your system, you can change the
default using the
mex -setup command. See Change Default Compiler and the
list of Supported
Compilers.

Running the acoustic_environment Model


Run the acoustic_environment model supplied with the tutorial
to understand the problem that you are trying to solve
using the LMS filter. This
model adds band-limited white noise to an audio signal and outputs the resulting
signal to a
speaker.

To simulate the model:

1. Open the acoustic_environment model in Simulink:


a. Set your MATLAB current folder to the folder that contains
your working files for this tutorial. At the MATLAB
command line,
enter:
cd work

where
work is the full path name of
the folder containing your files. See Find Files and Folders for more
information.
b. At the MATLAB command line,
enter:
acoustic_environment

2. Ensure that your speakers are on.


3. To simulate the model, from the Simulink model window, click Run.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 4/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

As Simulink runs the model, you hear the audio signal distorted by
noise.
4. While the simulation is running, double-click the Manual
Switch to select the audio source.
Now you hear the desired audio input without any noise.

The goal of this tutorial is to use a MATLAB LMS filter algorithm to remove the noise from the noisy audio signal.
You do
this by adding a MATLAB Function block to the model and
calling the MATLAB code from this block.

Adding a MATLAB Function Block to Your Model


To modify the model and code yourself, work through the exercises in this section.
Otherwise, open the supplied model
noise_cancel_01 in your
solutions subfolder to see the modified model.

For the purposes of this tutorial, you add the MATLAB Function
block to the noise_cancel_00 model supplied with the
tutorial. In
practice, you would have to develop your own test bench starting with an empty
Simulink model.

To add a MATLAB Function block to the


noise_cancel_00 model:

1. Open noise_cancel_00 in Simulink.


noise_cancel_00

2. Add a MATLAB Function block to the model:


a. At the MATLAB command line, type
slLibraryBrowser to open the
Simulink Library Browser.
b. From the list of Simulink libraries, select the User-Defined
Functions library.
c. Click the MATLAB Function block and drag it
into the noise_cancel_00 model. Place the
block just above the red
text annotation Place
MATLAB Function Block here.
d. Delete the red text annotations from the model.
e. Save the model in the current folder as
noise_cancel_01.
 Best Practice — Saving Incremental Code
Updates

Calling Your MATLAB Code As an Extrinsic Function for Rapid Prototyping


In this part of the tutorial, you use the coder.extrinsic
function to call your MATLAB code from the MATLAB Function
block for rapid
prototyping.

Why Call MATLAB Code As an Extrinsic Function?.  Calling MATLAB code as an extrinsic function provides these benefits:

• For rapid prototyping, you do not have to make the MATLAB code suitable for code generation.
• Using coder.extrinsic enables you to debug
your MATLAB code in MATLAB. You can add one or more breakpoints in
the
lms_01.m file, and then start the simulation
in Simulink. When the MATLAB execution engine encounters a
breakpoint, it
temporarily halts execution so that you can inspect the MATLAB workspace and view the current values of
all variables
in memory. For more information about debugging MATLAB code, see Debug a MATLAB Program.

How to Call MATLAB Code As an Extrinsic Function.   To call your MATLAB code from the MATLAB Function block:

1. Double-click the MATLAB Function block to open the


MATLAB Function Block Editor.
2. Delete the default code displayed in the MATLAB Function Block
Editor.
3. Copy the following code to the MATLAB Function
block.
function [ Signal_Out, Weights ] = LMS(Noise_In, Signal_In) %#codegen

% Extrinsic:

coder.extrinsic('lms_01');

% Compute LMS:

[ ~, Signal_Out, Weights ] = lms_01(Noise_In, Signal_In);

end

 Why Use the Tilde (~) Operator?


4. Save the model.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 5/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

The lms_01 function inputs


Noise_In and Signal_In now
appear as input ports to the block and the function outputs
Signal_Out and Weights
appear as output ports.

Connecting the MATLAB Function Block Inputs and Outputs

1. Connect the MATLAB Function block inputs and outputs so


that your model looks like this.

2. In the MATLAB Function block code, preallocate the


outputs by adding the following code after the extrinsic
call:
% Outputs:

Signal_Out = zeros(size(Signal_In));

Weights = zeros(32,1);

The
size of Weights is set to match the Numerator
coefficients of the Digital Filter in the Acoustic Environment
subsystem.
 Why Preallocate the Outputs?
 Modified MATLAB Function Block Code
3. Save the model.
You are now ready to check your model for errors.

Simulating the noise_cancel_01 Model


To simulate the model:

1. Ensure that you can see the Time Domain plots.


To view the plots, in the noise_cancel_01 model, open
the Analysis and Visualization block and then open the
Time
Domain block.
2. In the Simulink model window, click Run.
As Simulink runs the model, you see and hear outputs. Initially, you hear
the audio signal distorted by noise. Then the
filter attenuates the noise
gradually, until you hear only the music playing with very little noise
remaining. After two
seconds, you hear the distorted noisy signal again and
the filter attenuates the noise again. This cycle repeats
continuously.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 6/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

MATLAB displays the following plot showing this cycle.

3. Stop the simulation.

 Why Does the Filter Reset Every 2 Seconds?

Modifying the Filter to Use Streaming


• What Is Streaming?
• Why Use Streaming?
• Viewing the Modified MATLAB Code
• Summary of Changes to the Filter Algorithm
• Modifying Your Model to Call the Updated Algorithm
• Simulating the Streaming Algorithm

What Is Streaming?.  A streaming filter is called repeatedly to process fixed-size chunks of input
data, or frames, until it has
processed the entire input
signal. The frame size can be as small as a single sample, in which case the
filter would be
operating in a sample-based mode, or up to a few thousand
samples, for frame-based processing.

Why Use Streaming?.  The design of the filter algorithm in lms_01 has the
following disadvantages:

• The algorithm does not use memory efficiently.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 7/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

Preallocating a fixed amount of memory for each input signal for


the lifetime of the program means more memory is
allocated than is
in use.
• You must know the size of the input signal at the time you call
the function.
If the input signal is arriving in real time or as a stream of
samples, you would have to wait to accumulate the entire
signal
before you could pass it, as a batch, to the filter.
• The signal size is limited to a maximum size.

In an embedded application, the filter is likely to be processing a continuous


input stream. As a result, the input signal can
be substantially longer than the
maximum length that a filter working in batch mode could possibly handle. To
make the
filter work for any signal length, it must run in real time. One
solution is to convert the filter from batch-based processing to
stream-based
processing.

Viewing the Modified MATLAB Code.  The conversion to streaming involves:

• Introducing a first-in, first-out (FIFO) queue


The FIFO queue acts as a temporary storage buffer, which holds a
small number of samples from the input data stream.
The number of
samples held by the FIFO queue must be exactly the same as the
number of samples in the filter's
impulse response, so that the
function can perform the convolution operation between the filter
coefficients and the
input signal.
• Making the FIFO queue and the filter weights persistent
The filter is called repeatedly until it has processed the entire
input signal. Therefore, the FIFO queue and filter weights
need to
persist so that the adaptation process does not have to start over
again after each subsequent call to the
function.

Open the supplied file lms_02.m in your


work subfolder to see the modified algorithm.

 Contents of lms_02.m

Summary of Changes to the Filter Algorithm.  Note the following important changes to the filter algorithm:

• The filter weights and the FIFO queue are declared as


persistent:
persistent weights;

persistent fifo;

• The FIFO queue is


initialized:
fifo = zeros(FilterLength,ChannelCount);

• The FIFO queue is used in the filter update


loop:
% For each channel:

for ch = 1:ChannelCount

% For each sample time:

for n = 1:FrameSize

% Update the FIFO shift register:

fifo(1:FilterLength-1,ch) = fifo(2:FilterLength,ch);

fifo(FilterLength,ch) = signal_in(n,ch);

% Compute the output sample using convolution:

signal_out(n,ch) = weights' * fifo(:,ch);

% Update the filter coefficients:

err(n,ch) = desired(n,ch) - signal_out(n,ch) ;

weights = weights + mu*err(n,ch)*fifo(:,ch);

end

end

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 8/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

• You cannot output a persistent variable. Therefore, a new


variable, weights_out, is used to output the
filter
weights:
function [ signal_out, err, weights_out ] = ...

lms_02(distorted, desired)

weights_out = weights;

Modifying Your Model to Call the Updated Algorithm.  To modify the model yourself, work through the exercises in this
section.
Otherwise, open the supplied model noise_cancel_02 in your
solutions subfolder to see the modified
model.

1. In the noise_cancel_01 model, double-click the


MATLAB Function block to open the MATLAB Function
Block Editor.
2. Modify the MATLAB Function block code to call
lms_02.
a. Modify the extrinsic
call.
% Extrinsic:

coder.extrinsic('lms_02');

b. Modify the call to the filter


algorithm.
% Compute LMS:

[ ~, Signal_Out, Weights ] = lms_02(Noise_In, Signal_In);

 Modified MATLAB Function Block Code

3. Change the frame size from 16384 to


64, which represents a more realistic
value.
a. Right-click inside the model window and select
Model Properties.
b. Select the Callbacks tab.
c. In the Model callbacks list, select
InitFcn.
d. Change the value of FrameSize to
64.
e. Click Apply and close the dialog
box.

4. Save your model as noise_cancel_02.

Simulating the Streaming Algorithm.  To simulate the model:

1. Ensure that you can see the Time Domain


plots.
2. Start the simulation.
As Simulink runs the model, you see and hear outputs. Initially, you
hear the audio signal distorted by noise. Then,
during the first few
seconds, the filter attenuates the noise gradually, until you hear only
the music playing with very
little noise remaining. MATLAB displays the following plot showing filter convergence
after only a few seconds.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 9/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

3. Stop the simulation.

The filter algorithm is now suitable for Simulink. You are ready to elaborate your model to use
Adapt and Reset controls.

Adding Adapt and Reset Controls


• Why Add Adapt and Reset Controls?
• Modifying Your MATLAB Code
• Modifying Your Model to Use Reset and Adapt Controls
• Simulating the Model with Adapt and Reset Controls

Why Add Adapt and Reset Controls?.  In this part of the tutorial, you add Adapt and Reset controls to your filter.
Using these
controls, you can turn the filtering on and off. When
Adapt is enabled, the filter continuously updates the
filter weights.
When Adapt is disabled, the filter weights
remain at their current values. If Reset is set, the filter
resets the filter weights.

Modifying Your MATLAB Code.  To modify the code yourself, work through the exercises in this section.
Otherwise, open
the supplied file lms_03.m in your
solutions subfolder to see the modified
algorithm.

To modify your filter code:

1. Open lms_02.m.
2. In the Set up section, replace
if ( isempty(weights) )
https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 10/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

with
if ( reset || isempty(weights) )

3. In the filter loop, update the filter coefficients only if


Adapt is
ON.
if adapt

weights = weights + mu*err(n,ch)*fifo(:,ch);

end

4. Change the function signature to use the Adapt


and Reset inputs and change the function name to
lms_03.
function [ signal_out, err, weights_out ] = ...

lms_03(signal_in, desired, reset, adapt)

5. Save the file in the current folder as


lms_03.m:

 Contents of lms_03.m

 Summary of Changes to the Filter Algorithm

Modifying Your Model to Use Reset and Adapt Controls.  To modify the model yourself, work through the exercises in this
section.
Otherwise, open the supplied model noise_cancel_03 in your
solutions subfolder to see the modified
model.

1. Open the noise_cancel_02 model.


2. Double-click the MATLAB Function block to open the
MATLAB Function Block Editor.
3. Modify the MATLAB Function block code:
a. Update the function declaration.
function [ Signal_Out, Weights ] = ...

LMS(Adapt, Reset, Noise_In, Signal_In )

b. Update the extrinsic


call.
coder.extrinsic('lms_03');

c. Update the call to the LMS


algorithm.
% Compute LMS:

[ ~, Signal_Out, Weights ] = ...

lms_03(Noise_In, Signal_In, Reset, Adapt);

d. Close the MATLAB Function Block Editor.


The lms_03 function inputs
Reset and Adapt
now appear as input ports to the MATLAB
Function block.

4. Open the design_templates model.

5. Copy the Settings block from this model to your


noise_cancel_02 model:
a. From the design_templates model menu,
select Edit > Select All.
b. Select Edit > Copy.
c. From the noise_cancel_02 model menu,
select Edit > Paste.

6. Connect the Adapt and Reset outputs of the Settings subsystem to the
corresponding inputs on the MATLAB Function
block. Your
model should now appear as follows.
https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 11/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

7. Save the model as noise_cancel_03.

Simulating the Model with Adapt and Reset Controls.  To simulate the model and see the effect of the Adapt and Reset
controls:

1. In the noise_cancel_03 model, view the


Convergence scope:
a. Double-click the Analysis and Visualization
subsystem.
b. Double-click the Convergence scope.

2. In the Simulink model window, click Run.


Simulink runs the model as before. While the model is running,
toggle the Adapt and Reset controls and view the
Convergence scope
to see their effect on the filter.
The filter converges when Adapt is
ON and Reset is
OFF, then resets when you
toggleReset. The results might look
something
like this:

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 12/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

3. Stop the simulation.

Generating Code
You have proved that your algorithm works in Simulink. Next you generate code for your model. Before generating code, you
must ensure that your MATLAB code is suitable for code generation. For code generation, you must
remove the extrinsic
call to your code.

Making Your Code Suitable for Code Generation.  To modify the model and code yourself, work through the exercises in
this
section. Otherwise, open the supplied model noise_cancel_04
and file lms_04.m in your
solutions subfolder to see
the
modifications.

1. Rename the MATLAB Function block to


LMS_Filter. Select the annotation MATLAB
Function below the MATLAB
Function block
and replace the text with LMS_Filter.
When you generate code for the MATLAB Function block,
Simulink
Coder uses the name of the block in the generated
code. It is
good practice to use a meaningful name.
2. In your noise_cancel_03 model, double-click the
MATLAB Function block.
The MATLAB Function Block Editor opens.
3. Delete the extrinsic
declaration.
% Extrinsic:

coder.extrinsic('lms_03');

4. Delete the preallocation of


outputs.
% Outputs:

Signal_Out = zeros(size(Signal_In));

Weights = zeros(32,1);

5. Modify the call to the filter


algorithm.
% Compute LMS:

[ ~, Signal_Out, Weights ] = ...

lms_04(Noise_In, Signal_In, Reset, Adapt);

6. Save the model as noise_cancel_04.


7. Open lms_03.m
a. Modify the function name to
lms_04.

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 13/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

b. Turn on error checking specific to code generation by


adding the %#codegen compilation
directive after the
function declaration.
function [ signal_out, err, weights_out ] = ...

lms_04(signal_in, desired, reset, adapt) %#codegen

The code analyzer message indicator in the top right turns


red to indicate that the code analyzer has detected code
generation issues. The code analyzer underlines the
offending code in red and places a red marker to the right
of it.

8. Move your pointer over the first red marker to view the error
information.
The code analyzer detects that code generation requires
signal_out to be fully defined before
subscripting it and does
not support growth of variable size data
through indexing.
9. Move your pointer over the second red marker and note that the code
analyzer detects the same errors for err.
10. To address these errors, preallocate the outputs
signal_out and err. Add this
code after the filter
setup.
% Output Arguments:

% Pre-allocate output and error signals:

signal_out = zeros(FrameSize,ChannelCount);

err = zeros(FrameSize,ChannelCount);

 Why Preallocate the Outputs?


The red error markers for the two lines of code disappear. The code
analyzer message indicator in the top right edge of
the code turns
green, which indicates that you have fixed all the errors and warnings
detected by the code analyzer.
 Contents of lms_04.m
11. Save the file as lms_04.m.

Generating Code for noise_cancel_04

1. Before generating code, ensure that Simulink


Coder creates a code generation report. This HTML report
provides easy
access to the list of generated files with a summary of
the configuration settings used to generate the code.
a. In the Simulink model window, in the Modeling
tab, click Model Settings.
b. In the left pane of the Configuration Parameters dialog box,
select Code Generation > Report.
c. In the right pane, select Create code generation
report and Open report
automatically.
d. Click Apply and close the Configuration
Parameters dialog box.
e. Save your model.

2. To generate code for the LMS Filter subsystem:


a. In your model, select the LMS Filter subsystem.
b. From the Build Model tool menu, select Build
Selected Subsystem.

The Build code for subsystem dialog box


appears. Click the Build button.
The Simulink
Coder software generates C code for the subsystem and
opens the code generation report.
For more information on using the code generation report, see
Generate a Code Generation Report (Simulink
Coder).
c. In the left pane of the code generation report, click the
LMS_Filter.c link to view the generated C
code. Note that
the lms_04 function has no
code because inlining is enabled by default.

3. Modify your filter algorithm to disable inlining:


a. In lms_04.m, after the function
declaration,
add:
https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 14/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

coder.inline('never')

b. Change the function name to lms_05 and


save the file as lms_05.m in the current
folder.
c. In your noise_cancel_04 model,
double-click the MATLAB Function
block.
The MATLAB Function Block Editor opens.
d. Modify the call to the filter algorithm to call
lms_05.
% Compute LMS:

[ ~, Signal_Out, Weights ] = ...

lms_05(Noise_In, Signal_In, Reset, Adapt);

e. Save the model as


noise_cancel_05.

4. Generate code for the updated model.


a. In the model, select the LMS Filter subsystem.
b. From the Build Model tool menu, select Build
Selected Subsystem.
The Build code for subsystem dialog
box appears.
c. Click the Build button.
The Simulink
Coder software generates C code for the subsystem
and opens the code generation report.
d. In the left pane of the code generation report, click the
LMS_Filter.c link to view the
generated C code.
This time the lms_05 function has code
because you disabled
inlining.
/* Forward declaration for local functions */

static void LMS_Filter_lms_05 ...

(const real_T signal_in[64],const real_T ...

desired[64], real_T reset, real_T adapt, ...

real_T signal_out[64], ...

real_T err[64], real_T weights_out[32]);

/* Function for MATLAB Function Block: 'root/LMS_Filter' */

static void LMS_Filter_lms_05 ...

(const real_T signal_in[64], const real_T ...

desired[64], real_T reset, real_T adapt, ...

real_T signal_out[64], ...

real_T err[64], real_T weights_out[32])

Optimizing the LMS Filter Algorithm


This part of the tutorial demonstrates when and how to preallocate memory for a
variable without incurring the overhead of
initializing memory in the generated
code.

In lms_05.m, the MATLAB code not only declares signal_out and


err to be a
FrameSize-by-ChannelCount vector of real
doubles, but also initializes each element of signal_out and
err to zero. These signals are initialized to zero in the
generated C code.

MATLAB Code Generated C Code

% Pre-allocate output and error


signals: /* Pre-allocate output and error signals: */

signal_out =
zeros(FrameSize,ChannelCount);
79 for (i = 0; i <
64; i++) {

err =
zeros(FrameSize,ChannelCount); 80
signal_out[i] = 0.0;

81
err[i] = 0.0;

82
}

This forced initialization is unnecessary because both


signal_out and err are explicitly
initialized in the MATLAB code
before they are read.

 Note

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 15/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

You should not use coder.nullcopy when declaring the


variables weights and fifo because these
variables
need to be initialized in the generated code. Neither variable is
explicitly initialized in the MATLAB code before they
are read.

Use coder.nullcopy in the declaration of


signal_out and err to eliminate the
unnecessary initialization of memory in
the generated code:

1. In lms_05.m, preallocate
signal_out and err using
coder.nullcopy:
% Pre-allocate output and error signals:

signal_out = coder.nullcopy(zeros(FrameSize, ChannelCount));

err = coder.nullcopy(zeros(FrameSize, ChannelCount));

 Caution
After declaring a variable with
coder.nullcopy, you must explicitly
initialize the variable in your MATLAB
code before reading it. Otherwise, you might get
unpredictable results.

2. Change the function name to lms_06 and save the


file as lms_06.m in the current folder.
3. In your noise_cancel_05 model, double-click the
MATLAB Function block.
The MATLAB Function Block Editor opens.
4. Modify the call to the filter
algorithm.
% Compute LMS:

[ ~, Signal_Out, Weights ] = ...

lms_06(Noise_In, Signal_In, Reset, Adapt);

5. Save the model as noise_cancel_06.

Generate code for the updated model.

1. Select the LMS Filter subsystem.


2. From the Build Model tool menu, select Build Selected
Subsystem.
The Build code for subsystem dialog box appears.
Click the Build button.
The Simulink
Coder software and generates C code for the subsystem and opens
the code generation report.
3. In the left pane of the code generation report, click the
LMS_Filter.c link to view the generated C
code.
In the generated C code, this time there is no initialization to zero
of signal_out and err.

See Also
coder.extrinsic

Related Examples
• Create Custom Functionality Using MATLAB Function Block
• Track Object Using MATLAB Code

More About
• Implementing MATLAB Functions Using Blocks
• MATLAB Function Block Editor
• MATLAB Function Reports

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 16/17
6/11/2021 Filter Audio Signal Using MATLAB Code - MATLAB & Simulink

https://www.mathworks.com/help/simulink/ug/tutorial-integrating-matlab-code-with-a-simulink-model-for-filtering-an-audio-signal.html 17/17

You might also like