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.
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 Simple Model.
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).
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.
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
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?
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);
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);
Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc., 1996.
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.
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.
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 files | acoustic_environment | Simulink model that provides an overview of the acoustic 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. |
Copy the tutorial files to a local folder:
Create a local solutions
folder,
for example, c:\test\lms\solutions
.
Change to the docroot\toolbox\simulink\examples
folder.
At the MATLAB command line, enter:
cd(fullfile(docroot, 'toolbox', 'simulink', 'examples'))
Copy the contents of the lms
subfolder
to your solutions
folder, specifying the
full path name of the solutions
folder:
copyfile('lms', 'solutions')
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.Create a local work
folder,
for example, c:\test\lms\work
.
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.
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 (MATLAB) and the list of Supported
Compilers.
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:
Open the acoustic_environment
model
in Simulink:
Set your MATLAB current folder to the folder that contains your working files for this tutorial. At the MATLAB command line, enter:
cd work
work
is
the full path name of the folder containing your files. See Find Files and Folders (MATLAB) for
more information.At the MATLAB command line, enter:
acoustic_environment
Ensure that your speakers are on.
To simulate the model, from the Simulink model window, select Simulation > Run.
As Simulink runs the model, you hear the audio signal distorted by noise.
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.
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:
Open noise_cancel_00
in Simulink.
noise_cancel_00
Add a MATLAB Function block to the model:
At the MATLAB command line, type slLibraryBrowser
to
open the Simulink Library Browser.
From the list of Simulink libraries, select the User-Defined
Functions
library.
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
.
Delete the red text annotations from the model.
Save the model in the current folder as noise_cancel_01
.
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 (MATLAB).
How to Call MATLAB Code As an Extrinsic Function. To call your MATLAB code from the MATLAB Function block:
Double-click the MATLAB Function block to open the MATLAB Function Block Editor.
Delete the default code displayed in the MATLAB Function Block Editor.
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
Save the model.
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
Connect the MATLAB Function block inputs and outputs so that your model looks like this.
See Block and Signal Line Shortcuts and Actions for more information.
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);
Weights
is
set to match the Numerator coefficients of the Digital Filter in the
Acoustic Environment subsystem.
Save the model.
You are now ready to check your model for errors.
To simulate the model:
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.
In the Simulink model window, select Simulation > 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.
MATLAB displays the following plot showing this cycle.
Stop the simulation.
Why Does the Filter Reset Every 2 Seconds?
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.
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.
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
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.
In the noise_cancel_01
model, double-click
the MATLAB Function block to open the MATLAB Function
Block Editor.
Modify the MATLAB Function block code
to call lms_02
.
Modify the extrinsic call.
% Extrinsic: coder.extrinsic('lms_02');
Modify the call to the filter algorithm.
% Compute LMS: [ ~, Signal_Out, Weights ] = lms_02(Noise_In, Signal_In);
Change the frame size from 16384
to 64
,
which represents a more realistic value.
Right-click inside the model window and select Model Properties from the context menu.
Select the Callbacks tab.
In the Model callbacks list,
select InitFcn
.
Change the value of FrameSize
to 64
.
Click Apply and close the dialog box.
Save your model as noise_cancel_02
.
Simulating the Streaming Algorithm. To simulate the model:
Ensure that you can see the Time Domain plots.
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.
Stop the simulation.
The filter algorithm is now suitable for Simulink. You
are ready to elaborate your model to use 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:
Open lms_02.m
.
In the Set up
section, replace
if ( isempty(weights) )
if ( reset || isempty(weights) )
In the filter loop, update the filter coefficients
only if Adapt
is ON
.
if adapt weights = weights + mu*err(n,ch)*fifo(:,ch); end
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)
Save the file in the current folder as 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.
Open the noise_cancel_02
model.
Double-click the MATLAB Function block to open the MATLAB Function Block Editor.
Modify the MATLAB Function block code:
Update the function declaration.
function [ Signal_Out, Weights ] = ... LMS(Adapt, Reset, Noise_In, Signal_In )
Update the extrinsic call.
coder.extrinsic('lms_03');
Update the call to the LMS algorithm.
% Compute LMS: [ ~, Signal_Out, Weights ] = ... lms_03(Noise_In, Signal_In, Reset, Adapt);
Close the MATLAB Function Block Editor.
The lms_03
function inputs Reset
and Adapt
now
appear as input ports to the MATLAB Function block.
Open the design_templates
model.
Copy the Settings block from this model to your noise_cancel_02
model:
From the design_templates
model
menu, select Edit > Select
All.
Select Edit > Copy.
From the noise_cancel_02
model
menu, select Edit > Paste.
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.
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:
In the noise_cancel_03
model, view
the Convergence scope:
Double-click the Analysis and Visualization subsystem.
Double-click the Convergence scope.
In the Simulink model window, select Simulation > 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:
Stop the simulation.
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.
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.
In your noise_cancel_03
model,
double-click the MATLAB Function block.
The MATLAB Function Block Editor opens.
Delete the extrinsic declaration.
% Extrinsic: coder.extrinsic('lms_03');
Delete the preallocation of outputs.
% Outputs: Signal_Out = zeros(size(Signal_In)); Weights = zeros(32,1);
Modify the call to the filter algorithm.
% Compute LMS: [ ~, Signal_Out, Weights ] = ... lms_04(Noise_In, Signal_In, Reset, Adapt);
Save the model as noise_cancel_04
.
Open lms_03.m
Modify the function name to lms_04
.
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.
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.
Move your pointer over the second red marker and note
that the code analyzer detects the same errors for err
.
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);
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.
Save the file as lms_04.m
.
Generating Code for noise_cancel_04
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.
In the Simulink model window, select Simulation > Model Configuration Parameters.
In the left pane of the Configuration Parameters dialog box, select Code Generation > Report.
In the right pane, select Create code generation report.
The Launch report automatically option is also selected.
Click Apply and close the Configuration Parameters dialog box.
Save your model.
To generate code for the LMS Filter subsystem:
In your model, select the LMS Filter subsystem.
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 launches the code generation report.
For more information on using the code generation report, see Generate a Code Generation Report (Simulink Coder) in the Simulink Coder documentation.
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.
Modify your filter algorithm to disable inlining:
In lms_04.m
, after the function
declaration, add:
coder.inline('never')
Change the function name to lms_05
and
save the file as lms_05.m
in the current folder.
In your noise_cancel_04
model,
double-click the MATLAB Function block.
The MATLAB Function Block Editor opens.
Modify the call to the filter algorithm to call lms_05
.
% Compute LMS: [ ~, Signal_Out, Weights ] = ... lms_05(Noise_In, Signal_In, Reset, Adapt);
Save the model as noise_cancel_05
.
Generate code for the updated model.
In the model, select the LMS Filter subsystem.
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 launches the code generation report.
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]) |
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: signal_out = zeros(FrameSize,ChannelCount); err = zeros(FrameSize,ChannelCount); | /* Pre-allocate output and error signals: */ 79 for (i = 0; i < 64; i++) { 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:
You should not use |
Use coder.nullcopy
in the declaration of signal_out
and err
to
eliminate the unnecessary initialization of memory in the generated
code:
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 |
Change the function name to lms_06
and
save the file as lms_06.m
in the current folder.
In your noise_cancel_05
model,
double-click the MATLAB Function block.
The MATLAB Function Block Editor opens.
Modify the call to the filter algorithm.
% Compute LMS: [ ~, Signal_Out, Weights ] = ... lms_06(Noise_In, Signal_In, Reset, Adapt);
Save the model as noise_cancel_06
.
Generate code for the updated model.
Select the LMS Filter subsystem.
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 launches the code generation report.
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
.