Professional Documents
Culture Documents
• 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
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).
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.
lms_01(signal_in, desired)
for n = 1:SignalLength
end
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
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.
Simulink model acoustic_environment Simulink model that provides an overview of the acoustic
files environment.
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
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
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
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.
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.
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:
% Extrinsic:
coder.extrinsic('lms_01');
% Compute LMS:
end
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
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.
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
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:
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
Contents of lms_02.m
Summary of Changes to the Filter Algorithm. Note the following important changes to the filter algorithm:
persistent fifo;
for ch = 1:ChannelCount
for n = 1:FrameSize
fifo(1:FilterLength-1,ch) = fifo(2:FilterLength,ch);
fifo(FilterLength,ch) = signal_in(n,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
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.
coder.extrinsic('lms_02');
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
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.
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) )
end
Contents of lms_03.m
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.
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
Simulating the Model with Adapt and Reset Controls. To simulate the model and see the effect of the Adapt and Reset
controls:
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
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.
coder.extrinsic('lms_03');
Signal_Out = zeros(size(Signal_In));
Weights = zeros(32,1);
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
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:
signal_out = zeros(FrameSize,ChannelCount);
err = zeros(FrameSize,ChannelCount);
coder.inline('never')
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
}
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
1. In lms_05.m, preallocate
signal_out and err using
coder.nullcopy:
% Pre-allocate output and error signals:
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.
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