DSP System Toolbox™ User's Guide
DSP System Toolbox™ User's Guide
DSP System Toolbox™ User's Guide
Users Guide
R2014a
Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com
comp.soft-sys.matlab
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
DSP System Toolbox Users Guide
COPYRIGHT 20112014 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
governments needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
First printing
Online only
Online only
Online only
Online only
Online only
Online only
Revised
Revised
Revised
Revised
Revised
Revised
Revised
for
for
for
for
for
for
for
Version
Version
Version
Version
Version
Version
Version
8.0
8.1
8.2
8.3
8.4
8.5
8.6
(R2011a)
(R2011b)
(R2012a)
(R2012b)
(R2013a)
(R2013b)
(R2014a)
Contents
Input, Output, and Display
1
Discrete-Time Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time and Frequency Terminology . . . . . . . . . . . . . . . . . . . .
Recommended Settings for Discrete-Time Simulations . . .
Other Settings for Discrete-Time Simulations . . . . . . . . . .
1-2
1-2
1-4
1-6
Continuous-Time Signals . . . . . . . . . . . . . . . . . . . . . . . . . . .
Continuous-Time Source Blocks . . . . . . . . . . . . . . . . . . . . . .
Continuous-Time Nonsource Blocks . . . . . . . . . . . . . . . . . .
1-11
1-11
1-11
1-13
1-13
1-16
1-19
1-19
1-22
1-26
1-26
1-32
1-32
1-33
1-36
1-36
1-26
1-29
1-39
vi
Contents
1-43
1-43
1-52
1-52
1-56
1-59
1-64
1-64
1-67
1-72
1-72
1-72
1-77
1-78
1-85
1-86
1-88
1-91
1-96
1-104
1-104
1-105
1-107
1-48
1-73
2
Sample- and Frame-Based Concepts . . . . . . . . . . . . . . . . .
Sample- and Frame-Based Signals . . . . . . . . . . . . . . . . . . .
Model Sample- and Frame-Based Signals in MATLAB and
Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is Sample-Based Processing? . . . . . . . . . . . . . . . . . . .
What Is Frame-Based Processing? . . . . . . . . . . . . . . . . . . . .
2-2
2-2
2-8
2-8
2-10
2-12
2-15
2-16
2-20
2-20
2-21
2-25
2-29
2-35
2-38
2-41
2-45
2-45
2-45
2-61
2-61
2-63
2-63
2-3
2-4
2-5
2-49
2-53
2-56
2-57
vii
2-66
2-70
2-72
3
Design a Filter in Fdesign Process Overview . . . . . .
Process Flow Diagram and Filter Design Methodology . . .
3-2
3-2
3-11
3-11
3-16
3-16
3-21
3-23
3-31
3-38
3-43
3-49
3-54
3-59
3-60
3-60
3-70
3-84
viii
Contents
3-123
3-123
3-124
3-126
3-127
3-128
3-134
3-134
3-134
3-143
3-144
3-147
3-147
3-148
3-149
3-150
3-155
3-155
3-157
Adaptive Filters
4
Overview of Adaptive Filters and Applications . . . . . . .
Introduction to Adaptive Filtering . . . . . . . . . . . . . . . . . . . .
Adaptive Filtering Methodology . . . . . . . . . . . . . . . . . . . . . .
Choosing an Adaptive Filter . . . . . . . . . . . . . . . . . . . . . . . . .
System Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inverse System Identification . . . . . . . . . . . . . . . . . . . . . . . .
Noise or Interference Cancellation . . . . . . . . . . . . . . . . . . . .
Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-2
4-2
4-2
4-4
4-6
4-6
4-7
4-8
4-10
4-14
4-14
4-16
4-19
4-10
4-10
4-13
ix
4-22
4-26
4-30
4-35
4-35
4-36
4-41
4-41
4-42
4-43
4-44
4-44
4-44
4-45
4-46
4-47
4-47
4-48
4-49
4-51
4-51
Selected Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-66
4-53
4-59
4-64
5
Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Why Are Multirate Filters Needed? . . . . . . . . . . . . . . . . . . .
Overview of Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . .
Contents
5-2
5-2
5-2
Multistage Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Why Are Multistage Filters Needed? . . . . . . . . . . . . . . . . . .
Optimal Multistage Filters in DSP System Toolbox . . . . . .
5-6
5-6
5-6
5-8
5-8
5-8
5-9
5-9
5-10
Filter Banks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dyadic Analysis Filter Banks . . . . . . . . . . . . . . . . . . . . . . . .
Dyadic Synthesis Filter Banks . . . . . . . . . . . . . . . . . . . . . . .
5-12
5-12
5-16
5-21
6
Transform Time-Domain Data into Frequency
Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-2
6-7
6-13
6-13
6-13
6-15
6-15
6-17
6-19
6-20
6-22
xi
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-23
Spectral Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-24
6-25
6-25
6-26
6-33
Spectrograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modify the Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . .
Set the Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . .
View the Spectrogram of the Speech Signal . . . . . . . . . . . .
6-36
6-36
6-38
6-43
Mathematics
7
Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Statistics Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Basic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Running Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-2
7-2
7-3
7-4
7-6
7-6
7-6
7-8
7-9
Fixed-Point Design
8
Fixed-Point Signal Processing . . . . . . . . . . . . . . . . . . . . . .
Fixed-Point Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Benefits of Fixed-Point Hardware . . . . . . . . . . . . . . . . . . . .
xii
Contents
8-2
8-2
8-2
8-3
8-4
8-4
8-5
8-6
Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modulo Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Twos Complement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Addition and Subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . .
Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-10
8-10
8-11
8-12
8-13
8-16
8-21
8-21
8-25
8-26
8-27
8-28
8-28
8-31
8-32
8-43
Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scalar Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Vector Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-52
8-52
8-61
8-68
8-68
8-68
8-70
8-80
8-98
xiii
Code Generation
9
Understanding Code Generation . . . . . . . . . . . . . . . . . . . .
Code Generation with the Simulink Coder Product . . . . . .
Highly Optimized Generated ANSI C Code . . . . . . . . . . . . .
9-2
9-2
9-3
9-4
......................
9-12
9-13
9-13
9-15
9-15
9-18
9-19
xiv
Contents
9-24
9-24
9-24
9-31
9-32
9-33
9-33
9-33
9-41
9-41
9-41
9-43
9-43
9-45
...
9-47
9-49
10
Define Basic System Objects . . . . . . . . . . . . . . . . . . . . . . . .
10-3
10-5
10-8
xv
. . . . . . . . . . . . . . . . . . . . . . . 10-38
. . . . . . . . . . . . . . . . . . 10-47
. . . . . . . . . . . . . . . . . . . . . . . . . . 10-49
. . 10-72
xvi
Contents
10-75
10-76
10-76
10-77
11
Signal Management Library . . . . . . . . . . . . . . . . . . . . . . . .
11-2
.....................................
11-3
11-4
Filtering Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-5
Sinks Library
12
Lowpass FIR Filter Design . . . . . . . . . . . . . . . . . . . . . . . . .
12-2
12-7
xvii
13
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FDATool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filter Design Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using the Filter Design and Analysis Tool . . . . . . . . . . . . .
Analyzing Filter Responses . . . . . . . . . . . . . . . . . . . . . . . . .
Filter Design and Analysis Tool Panels . . . . . . . . . . . . . . . .
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13-2
13-2
13-2
13-4
13-4
13-4
13-5
Using FDATool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Choosing a Response Type . . . . . . . . . . . . . . . . . . . . . . . . . .
Choosing a Filter Design Method . . . . . . . . . . . . . . . . . . . . .
Setting the Filter Design Specifications . . . . . . . . . . . . . . .
Computing the Filter Coefficients . . . . . . . . . . . . . . . . . . . .
Analyzing the Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Editing the Filter Using the Pole/Zero Editor . . . . . . . . . . .
Converting the Filter Structure . . . . . . . . . . . . . . . . . . . . . .
Exporting a Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . .
Generating a C Header File . . . . . . . . . . . . . . . . . . . . . . . . .
Generating MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . .
Managing Filters in the Current Session . . . . . . . . . . . . . .
Saving and Opening Filter Design Sessions . . . . . . . . . . . .
13-6
13-7
13-8
13-8
13-12
13-13
13-19
13-23
13-26
13-32
13-34
13-35
13-38
14
Filterbuilder Design Process . . . . . . . . . . . . . . . . . . . . . . .
Introduction to Filterbuilder . . . . . . . . . . . . . . . . . . . . . . . .
xviii
Contents
14-2
14-2
14-2
14-3
14-5
14-5
14-7
14-9
14-9
Bibliography
A
Advanced Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-2
Adaptive Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-3
Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-4
Frequency Transformations . . . . . . . . . . . . . . . . . . . . . . . .
A-5
Fixed-Point Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-6
xix
xx
Contents
1
Input, Output, and Display
Learn how to input, output and display data and signals with DSP System
Toolbox.
Discrete-Time Signals on page 1-2
Continuous-Time Signals on page 1-11
Create Sample-Based Signals on page 1-13
Create Frame-Based Signals on page 1-19
Create Multichannel Sample-Based Signals on page 1-26
Create Multichannel Frame-Based Signals on page 1-32
Deconstruct Multichannel Sample-Based Signals on page 1-36
Deconstruct Multichannel Frame-Based Signals on page 1-43
Import and Export Sample-Based Signals on page 1-52
Import and Export Frame-Based Signals on page 1-64
Musical Instrument Digital Interface on page 1-72
Display Time-Domain Data on page 1-77
Display Frequency-Domain Data in Spectrum Analyzer on page 1-96
Visualize Central Limit Theorem in Array Plot on page 1-104
Discrete-Time Signals
In this section...
Time and Frequency Terminology on page 1-2
Recommended Settings for Discrete-Time Simulations on page 1-4
Other Settings for Discrete-Time Simulations on page 1-6
1-2
Discrete-Time Signals
Term
Symbol Units
Notes
Sample period
Ts
Tsi
Tso
Seconds
Frame period
Tf
Tfi
Tfo
Seconds
Signal period
Seconds
Sample
frequency
Fs
Hz (samples
per second)
Frequency
Hz (cycles
per second)
Hz (cycles
per second)
Nyquist rate
Nyquist
frequency
fnyq
Hz (cycles
per second)
Normalized
frequency
fn
Two cycles
per sample
Angular
frequency
Radians per
second
Digital
(normalized
angular)
frequency
Radians per
sample
Note In the Block Parameters dialog boxes, the term sample time is used to
refer to the sample period, Ts. For example, the Sample time parameter
in the Signal From Workspace block specifies the imported signals sample
period.
1-3
The selections that you make here determine how discrete-time signals are
processed in Simulink. The recommended Solver options settings for
signal processing simulations are
Type: Fixed-step
Solver: Discrete (no continuous states)
Fixed step size (fundamental sample time): auto
Tasking mode for periodic sample times: SingleTasking
1-4
Discrete-Time Signals
1-5
You can automatically set the above solver options for all new models by
running the dspstartup.m file. See Configure the Simulink Environment
for Signal Processing Models in the DSP System Toolbox Getting Started
Guide for more information.
In Fixed-step SingleTasking mode, discrete-time signals differ from the
prototype described in Time and Frequency Terminology on page 1-2 by
remaining defined between sample times. For example, the representation
of the discrete-time triangle wave looks like this.
The above signals value at t=3.112 seconds is the same as the signals value
at t=3 seconds. In Fixed-step SingleTasking mode, a signals sample times
are the instants where the signal is allowed to change values, rather than
where the signal is defined. Between the sample times, the signal takes on
the value at the previous sample time.
As a result, in Fixed-step SingleTasking mode, Simulink permits
cross-rate operations such as the addition of two signals of different rates.
This is explained further in Cross-Rate Operations on page 1-7.
1-6
Discrete-Time Signals
when operations attempt to reference the undefined region of a signal, as, for
example, when signals with different sample rates are added.
When the Variable-step solver is selected, discrete time signals remain
defined between sample times, just as in the Fixed-step SingleTasking
case described in Recommended Settings for Discrete-Time Simulations on
page 1-4. When the Variable-step solver is selected, cross-rate operations
are allowed by Simulink.
In the Fixed-step Auto setting, Simulink automatically selects a tasking
mode, single-tasking or multitasking, that is best suited to the model.
SeeSimulink Tasking Mode on page 2-70 for a description of the criteria
that Simulink uses to make this decision. For the typical model containing
multiple rates, Simulink selects the multitasking mode.
Cross-Rate Operations
When the Fixed-step MultiTasking solver is selected, discrete signals
in Simulink are undefined between sample times. Therefore, to perform
cross-rate operations like the addition of two signals with different sample
rates, you must convert the two signals to a common sample rate. Several
blocks in the Signal Operations and Multirate Filters libraries can accomplish
this task. See Convert Sample and Frame Rates in Simulink on page
2-20 for more information. Rate change can happen implicitly, depending
on diagnostic settings. See Multitask rate transition, Single task rate
transition. However, this is not recommended. By requiring explicit rate
conversions for cross-rate operations in discrete mode, Simulink helps you to
identify sample rate conversion issues early in the design process.
When the Variable-step solver or Fixed-step SingleTasking solver
is selected, discrete time signals remain defined between sample times.
Therefore, if you sample the signal with a rate or phase that is different from
the signals own rate and phase, you will still measure meaningful values:
1 At the MATLAB command line, type ex_sum_tut1.
The Cross-Rate Sum Example model opens. This model sums two signals
with different sample periods.
1-7
1-8
Discrete-Time Signals
Checking the Colors option allows you to see the different sampling rates
in action. For more information about the color coding of the sample times
see View Sample Time Information in the Simulink documentation.
7 Run the model.
The first column of the matrix is the fast signal, (Ts=1). The second column
of the matrix is the slow signal (Ts=2). The third column is the sum of the
1-9
two signals. As expected, the slow signal changes once every 2 seconds, half
as often as the fast signal. Nevertheless, the slow signal is defined at every
moment because Simulink holds the previous value of the slower signal
during time instances that the block doesnt run.
In general, for Variable-step and Fixed-step SingleTasking modes, when
you measure the value of a discrete signal between sample times, you are
observing the value of the signal at the previous sample time.
1-10
Continuous-Time Signals
Continuous-Time Signals
In this section...
Continuous-Time Source Blocks on page 1-11
Continuous-Time Nonsource Blocks on page 1-11
1-11
1-12
In this section...
Create Signals Using Constant Block on page 1-13
Create Signals Using Signal from Workspace Block on page 1-16
Constant value = [1 2 3; 4 5 6]
1-13
Dimensions.
8 Run the model and expand the Display block so you can view the entire
signal.
You have now successfully created a six-channel, constant sample-based
signal with a sample period of 1 second.
To view the model you just created, and to learn how to create a 1D vector
signal from the block diagram you just constructed, continue to the next
section.
you created in the previous section and paste it below the existing
sample-based signal in your model.
2 Double-click the Constant1 block, and set the block parameters as follows:
Constant value = [1 2 3 4 5 6]
Interpret vector parameters as 1D = Check this box
Sample time = 1
1-14
3 Save these parameters and close the dialog box by clicking OK.
4 Run the model and expand the Display1 block so you can view the entire
signal.
Your model should now look similar to the following figure. You can also
open this model by typing ex_usingcnstblksb at the MATLAB command
line.
1-15
the model.
4 Connect the two blocks.
5 Double-click the Signal From Workspace block, and set the block
parameters as follows:
Signal = cat(3,[1 -1;0 5],[2 -2;0 5],[3 -3;0 5])
Sample time = 1
Samples per frame = 1
Form output after final data value by = Setting to zero
Based on these parameters, the Signal From Workspace block outputs a
four-channel sample-based signal with a sample period of 1 second. After
the block has output the signal, all subsequent outputs have a value of
zero. The four channels contain the following values:
Channel 1: 1, 2, 3, 0, 0,...
Channel 2: -1, -2, -3, 0, 0,...
Channel 3: 0, 0, 0, 0, 0,...
Channel 4: 5, 5, 5, 0, 0,...
6 Save these parameters and close the dialog box by clicking OK.
1-16
7 From the Display menu, point to Signals & Ports, and select Signal
Dimensions.
8 Run the model.
-1
5
yout(:,:,2) =
2
0
-2
5
yout(:,:,3) =
3
0
-3
5
1-17
yout(:,:,4) =
0
0
0
0
1-18
In this section...
Create Signals Using Sine Wave Block on page 1-19
Create Signals Using Signal from Workspace Block on page 1-22
the model.
5 Connect the blocks in the order in which you added them to your model.
6 Double-click the Sine Wave block, and set the block parameters as follows:
Amplitude = [1 3 2]
1-19
Dimensions.
10 Run the model.
Your model should now look similar to the following figure. You can
also open the model by typing ex_usingsinwaveblkfb at the MATLAB
command line.
1-20
The three signals are summed point-by-point by a Matrix Sum block. Then,
they are exported to the MATLAB workspace.
11 At the MATLAB command line, type plot(yout(1:100)).
1-21
This figure represents a portion of the sum of the three sinusoids. You have
now added the channels of a three-channel frame-based signal together and
displayed the results in a figure window.
1-22
the model.
4 Connect the two blocks.
5 Double-click the Signal From Workspace block, and set the block
parameters as follows:
Signal = [1:10; 1 1 0 0 1 1 0 0 1 1]'
Sample time = 1
Samples per frame = 4
Form output after final data value by = Setting to zero
Based on these parameters, the Signal From Workspace block outputs a
two-channel, frame-based signal has a sample period of 1 second, a frame
period of 4 seconds, and a frame size of four samples. After the block
outputs the signal, all subsequent outputs have a value of zero. The two
channels contain the following values:
Channel 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0,...
Channel 2: 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,...
6 Save these parameters and close the dialog box by clicking OK.
7 From the Display menu, point to Signals & Ports, and select Signal
Dimensions.
8 Run the model.
1-23
1-24
1
1
0
0
1
1
7
8
9
10
0
0
0
0
1
1
0
0
Note that zeros were appended to the end of each channel. You have now
successfully created a two-channel frame-based signal and exported it to the
MATLAB workspace.
1-25
ex_cmbsnglchsbsigs
1-26
1-27
2 Double-click the Signal From Workspace block, and set the Signal
1-28
The 4-by-1 matrix output by the Matrix Concatenate block and the 2-by-2
matrix output by the Reshape block in the above model represent the same
four-channel sample-based signal. In some cases, one representation of the
signal may be more useful than the other.
9 At the MATLAB command line, type dsp_examples_yout.
ex_cmbmltichsbsigs
1-29
1-30
2 Double-click the Signal From Workspace block, and set the Signal
1-31
1-32
ex_combiningfbsigs
1-33
1-34
2 Double-click the Signal From Workspace block. Set the block parameters
as follows:
Signal = [1:10;-1:-1:-10]'
Sample time = 1
Samples per frame = 4
Based on these parameters, the Signal From Workspace block outputs a
frame-based signal with a frame size of four.
3 Save these parameters and close the dialog box by clicking OK.
4 Double-click the Signal From Workspace1 block. Set the block parameters
The 4-by-3 matrix output from the Matrix Concatenate block contains all
three input channels, and preserves their common frame rate and frame
size.
1-35
In this section...
Split Multichannel Signals into Individual Signals on page 1-36
Split Multichannel Signals into Several Multichannel Signals on page 1-39
1-36
2 Double-click the Signal From Workspace block, and set the block
parameters as follows:
1-37
Signal = randn(3,1,10)
Sample time = 1
Samples per frame = 1
Based on these parameters, the Signal From Workspace block outputs a
three-channel, sample-based signal with a sample period of 1 second.
3 Save these parameters and close the dialog box by clicking OK.
4 Double-click the Multiport Selector block. Set the block parameters as
1-38
This sample-based signal is the first row of the input to the Multiport
Selector block. You can view the other two input rows by typing
dsp_examples_yout1 and dsp_examples_yout2, respectively.
You have now successfully created three, single-channel sample-based signals
from a multichannel sample-based signal using a Multiport Selector block.
1-39
2 Double-click the Constant block, and set the block parameters as follows:
1-40
1-41
Notice that the output of the Submatrix block is equivalent to the matrix
created by rows three through five and columns six through seven of the
input matrix.
You have now successfully created a six-channel, sample-based signal from a
35-channel sample-based signal using a Submatrix block.
1-42
In this section...
Split Multichannel Signals into Individual Signals on page 1-43
Reorder Channels in Multichannel Frame-Based Signals on page 1-48
1-43
ex_splitmltichfbsigsind
1-44
1-45
2 Double-click the Signal From Workspace block, and set the block
parameters as follows:
Signal = [1:10;-1:-1:-10;5*ones(1,10)]'
Samples per frame = 4
Based on these parameters, the Signal From Workspace block outputs a
three-channel, frame-based signal with a frame size of four.
3 Save these parameters and close the dialog box by clicking OK.
4 Double-click the Multiport Selector block. Set the block parameters as
1-46
1-47
1-48
2 Double-click the Signal From Workspace block, and set the block
parameters as follows:
Signal = [1:10;-1:-1:-10;5*ones(1,10)]'
1-49
Sample time = 1
Samples per frame = 4
Based on these parameters, the Signal From Workspace block outputs a
three-channel, frame-based signal with a sample period of 1 second and a
frame size of 4. The frame period of this block is 4 seconds.
3 Save these parameters and close the dialog box by clicking OK.
4 Double-click the Constant block. Set the block parameters as follows, and
1-50
The second and third channel of the frame-based input signal are swapped.
7 At the MATLAB command line, type yout.
You can now verify that the second and third columns of the input signal
are rearranged.
You have now successfully reordered the channels of a frame-based signal
using the Permute Matrix block.
1-51
In this section...
Import Sample-Based Vector Signals on page 1-52
Import Sample-Based Matrix Signals on page 1-56
Export Sample-Based Signals on page 1-59
1-52
In the following example, you use the Signal From Workspace block to import
a sample-based vector signal into your model:
1 Open the Signal From Workspace Example 3 model by typing
1-53
1-54
parameters as follows:
Signal = [A B]
Sample time = 1
Samples per frame = 1
Form output after final data value = Setting to zero
The Signal expression [A B] uses the standard MATLAB syntax for
horizontally concatenating matrices and appends column vector B to the
right of matrix A. The Signal From Workspace block outputs a sample-based
signal with a sample period of 1 second. After the block has output the
signal, all subsequent outputs have a value of zero.
5 Save these parameters and close the dialog box by clicking OK.
6 Run the model.
The first row of the input matrix [A B] is output at time t=0, the second
row of the input matrix is output at time t=1, and so on.
You have now successfully imported a sample-based vector signal into your
signal processing model using the Signal From Workspace block.
1-55
In the following example, you use the Signal From Workspace block to import
a four-channel, sample-based matrix signal into a Simulink model:
1 Open the Signal From Workspace Example 4 model by typing
1-56
Also, the following variables are loaded into the MATLAB workspace:
1-57
Fs
1x1
double array
dsp_examples_A
2x2x100
3200
double array
dsp_examples_sig1
1x1x100
800
double array
dsp_examples_sig12
1x2x100
1600
double array
dsp_examples_sig2
1x1x100
800
double array
dsp_examples_sig3
1x1x100
800
double array
dsp_examples_sig34
1x2x100
1600
double array
dsp_examples_sig4
1x1x100
800
double array
mtlb
4001x1
32008
double array
2 Double-click the Signal From Workspace block. Set the block parameters
1-58
The Signal From Workspace block imports the four-channel sample based
signal from the MATLAB workspace into the Simulink model one matrix at
a time.
You have now successfully imported a sample-based matrix signal into your
model using the Signal From Workspace block.
1-59
The following figure is the graphical illustration of this process using a 6-by-4
sample-based signal exported to workspace array A.
The workspace array always has time running along its third dimension, P.
Samples are saved along the P dimension whether the input is a matrix,
vector, or scalar (single channel case).
In the following example you use a Signal To Workspace block to export a
sample-based matrix signal to the MATLAB workspace:
1 Open the Signal From Workspace Example 6 model by typing
1-60
Also, the following variables are loaded into the MATLAB workspace:
1-61
dsp_examples_A
2x2x100
3200
double array
dsp_examples_sig1
1x1x100
800
double array
dsp_examples_sig12
1x2x100
1600
double array
dsp_examples_sig2
1x1x100
800
double array
dsp_examples_sig3
1x1x100
800
double array
dsp_examples_sig34
1x2x100
1600
double array
dsp_examples_sig4
1x1x100
800
double array
1-62
-1
5
dsp_examples_yout(:,:,2) =
2
0
-2
5
dsp_examples_yout(:,:,3) =
3
0
-3
5
dsp_examples_yout(:,:,4) =
4
0
-4
5
Each page of the output represents a different sample time, and each element
of the matrices is in a separate channel.
You have now successfully exported a four-channel sample-based signal from
a Simulink model to the MATLAB workspace using the Signal To Workspace
block.
1-63
In this section...
Import Frame-Based Signals on page 1-64
Export Frame-Based Signals on page 1-67
1-64
ex_importfbsigs
1-65
2 Double-click the Signal From Workspace block. Set the block parameters
1-66
1-67
1-68
1-69
1-70
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
5
5
5
5
5
5
5
5
5
5
5
5
1-71
About MIDI
The Musical Instrument Digital Interface (MIDI) was originally developed to
interconnect electronic musical instruments. This interface is very flexible
and has many uses in many applications far beyond musical instruments.
Its simple unidirectional messaging protocol supports many different kinds
of messaging.
Windows, Macintosh, and Linux platforms all have native support for MIDI,
so software on any of these platforms can send and receive MIDI messages.
See http://www.midi.org for more information about MIDI.
1-72
1-73
Initial Setup
Your MIDI control surface should be connected to your computer, and turned
on, before starting MATLAB. Instructions for connecting your MIDI device to
your computer vary from device to device. See the instructions that came with
your particular device. If you start MATLAB before connecting your device,
MATLAB may not recognize your device when you connect it. To correct the
problem, restart MATLAB with the device already connected.
Next, set the MATLAB preference, specifying the name of the default MIDI
device. Use midiid to determine the name of the device, and then use
setpref to set the preference:
>> [control, device] = midiid
Move the control you wish to identify; type ^C to abort.
Waiting for control message... done
control =
1082
device =
BCF2000
>> setpref('midi', 'DefaultDevice', device)
>>
This preference persists across MATLAB sessions, so you only have to set it
once, unless you want to change devices.
If you do not set this preference, MATLAB and the host operating system
choose a device for you. However, such autoselection can cause unpredictable
results because many computers have virtual (software) MIDI devices
installed that you may not be aware of. For predictable behavior, you should
set the preference.
You can always override this default and explicitly specify a device name.
Thus, you can use multiple MIDI devices simultaneously.
Identifying Controls
Before you can connect a MIDI control with MATLAB or Simulink, you must
know the identifiers for that particular control:
Control number
1-74
Device name
The control number is a fixed integer assigned by the device manufacturer.
Some devices may change the assigned number based on various modes,
or you can reprogram the number. The device name is determined by the
manufacturer and the host operating system. You use midiid to determine
both.
You do not usually have to use midiid repeatedly. If you use a single device
in most cases, then specify that device as the default hardware. the You can
save the control numbers in a function, a .mat file, or whatever form you find
convenient. This example shows s a function returning a struct with all the
control numbers for a Behringer BCF2000:
function ctls = BCF2000
% BCF2000 return MIDI control number assignments
% for Behringer BCF2000 MIDI control surface
ctls.knobs = 1001:1008;
ctls.buttons = [1065:1072;1073:1080];
ctls.sliders = 1081:1088;
end
MATLAB Interface
To use the MATLAB interface functions, first call midicontrols to specify
any devices or controls to listen to. midicontrols returns an object, which
you pass to the other functions for subsequent operations. You can now
read the values of the specified MIDI controls by calling midiread with that
object. MATLAB can respond to changes in MIDI controls by periodically
calling midiread.
You can also set a callback on the specified MIDI controls by calling
midicallback with that object and a function handle. The next time the MIDI
controls change value, the function handle is invoked and passed to the object.
The callback function typically calls midiread to determine the new value of
the MIDI controls. You can use this callback when you want a MIDI control
to trigger an action (such as update a GUI). Using this approach prevents
having a continuously running MATLAB program in the command window.
1-75
Synchronization
If midiread is called before the MIDI control sends a Control Change
message, the midicontrols object has no information about the actual state
of the MIDI control. During this time, the midicontrols object and the actual
MIDI control are out of sync with each other. Thus, calling midiread returns
the initial value that was specified in the call to midicontrols (0 by default).
You can synchronize the object with the control by moving the MIDI control.
The MIDI control responds by sending a Control Change message causing the
midicontrols object to sync to the MIDI control. If your MIDI control surface is
bidirectional, you can sync in the other direction by calling midisync to send
the midicontrols objects initial value to the actual MIDI control. The MIDI
control responds by moving into sync with the midicontrols object.
It is generally harmless to call midisync even if the MIDI control surface is
not bidirectional, so it is usually good practice to call midisync immediately
after calling midicontrols.
Synchronization is also useful to link a MIDI control with a GUI control (a
uicontrol slider, for example), so that when one control is changed, the other
control tracks it. Typically, you implement such tracking by setting callback
functions on both the MIDI control (using midicallback) and the GUI control.
The MIDI control callback sends its new value to the GUI control and the GUI
control sends its value to the MIDI control, using midisync.
Simulink Interface
The MIDI Controls block provides the Simulink interface. See the block
reference page MIDI Controls for more details.
1-76
1-77
Use the following workflow to configure the Time Scope blocks in the
ex_timescope_tut model:
1 Configure the Time Scope Properties on page 1-78
2 Use the Simulation Controls on page 1-85
3 Modify the Time Scope Display on page 1-86
4 Inspect Your Data (Scaling the Axes and Zooming) on page 1-88
5 Manage Multiple Time Scopes on page 1-91
1-78
To open the Configuration Properties dialog box, you must first open the Time
Scope window by double-clicking the Time Scope block in your model. When
the window opens, select View > Configuration Properties. Alternatively,
in the Time Scope toolbar, click the Configuration Properties
button.
The Configuration Properties dialog box has four different tabs, Main, Time,
Display, and Logging, each of which offers you a different set of options.
For more information about the options available on each of the tabs, see
the Time Scope block reference page.
Note As you progress through this workflow, notice the blue question mark
icon (
) in the lower-left corner of the subsequent dialog boxes. This
icon indicates that context-sensitive help is available. You can get more
information about any of the parameters on the dialog box by right-clicking
the parameter name and selecting Whats This?
1-79
Setting
Open at
simulation
start
Number
of
input ports
Checked
Input
processing
Maximize
axes
Auto
Axes scaling
Manual
In this tutorial, you want the block to treat the input signal as frame-based,
so you must set the Input processing parameter to Columns as channels
(frame based).
1-80
Parameter
Description
Axes scaling
Select this check box to scale the axes when the simulation
stops. The y-axis is always scaled. The x-axis limits are
only scaled if you also select the Scale X-axis limits
check box.
1-81
Parameter
Description
Data range
(%)
Align
Setting
Axes scaling
Manual
Scale axes
limits at stop
Checked
Data range
(%)
80
Align
Center
Autoscale
X-axis limits
Unchecked
1-82
Parameter
Setting
Time span
Time span
overrun
action
Wrap
Time units
Time display
offset
Time-axis
labels
All
Show
time-axis
label
Checked
The Time span parameter allows you to enter a numeric value, a variable
that evaluates to a numeric value, or select the One frame period menu
option. You can also select the Auto menu option; in this mode, Time Scope
automatically calculates the appropriate value for time span from the
difference between the simulation Start time and Stop time parameters.
The actual range of values that the block displays on the time-axis depends on
the value of both the Time span and Time display offset parameters. See
the following figure.
If the Time display offset parameter is a scalar, the value of the minimum
time-axis limit is equal to the Time display offset. In addition, the value of
1-83
the maximum time-axis limit is equal to the sum of the Time display offset
parameter and the Time span parameter. For information on the other
parameters in the Time Scope window, see the Time Scope reference page.
In this tutorial, the values on the time-axis range from 0 to One frame
period, where One frame period is 0.05 seconds (50 ms).
Setting
Active display
Title
Show legend
Checked
Show grid
Checked
Unchecked
Y-limits (Minimum)
-2.5
Y-limits (Maximum)
2.5
Y-label
Amplitude
1-84
) on the
window, on the Simulation Toolbar, click the Run button (
Simulation Toolbar. You can also use one of the following keyboard
shortcuts:
Ctrl+T
P
Space
2 While the simulation is running and the Time Scope is your active window,
).
time step. To do so, in the Time Scope window, on the Simulation Toolbar,
click the Next Step button (
).
1-85
Next, try using keyboard shortcuts to achieve the same result. Press the
Page Down key to advance the simulation by a single time step.
4 Resume model simulation using any of the following methods:
).
1-86
Block Name
Original Signal
Name
Time Scope
Add
Time Scope
Time Scope1
Sine Wave
1 Change the Plot Type parameter to Auto for each Time Scope block.
This setting ensures that Time Scope displays a line graph if the signal is
continuous and a stairstep graph if the signal is discrete.
2 Change the Axes colors parameters for each Time Scope block. Leave the
axes background color as black and set the ticks, labels, and grid colors
to white.
3 Set the Properties for line parameter to the name of the signal for which
you would like to modify the line properties. Set the line properties for each
signal according to the values shown in the following table.
1-87
Block
Name
Signal
Name
Line
Line
Width
Marker Color
Time Scope
Noisy Sine
Wave
0.5
none
Time Scope
Filtered
Noisy Sine
Wave
0.5
Red
Time Scope1
Original
Sine Wave
0.5
Yellow
White
).
1-88
1-89
1-90
).
To zoom out of the Time Scope window, right-click inside the window, and
select Zoom Out. Alternatively, you can return to the original view of
your signal by right-clicking inside the Time Scope window and selecting
Reset to Original View.
1-91
Scope1 window opens, along with the already active Time Scope window. If
you have any Time Scope blocks in other open Simulink models, then these
also come into view.
1-92
The Time Scope window now appears in the Scopes group container. Next,
press the Dock Time Scope button at the top-right corner of the Time Scope
window for the Time Scope1 block.
By default, the Scopes group container is situated above the MATLAB
Command Window. However, you can undock the Scopes group container by
pressing the Show Actions button ( ) at the top-right corner of the container
and selecting Undock. The Scopes group container is now independent from
the MATLAB Command Window.
1-93
Once docked, the Scopes group container displays the toolbar and menu bar
of the Time Scope window. If you open additional instances of Time Scope, a
new Time Scope window appears in the Scopes group container.
You can undock any instance of Time Scope by pressing the corresponding
Undock button ( ) in the title bar of each docked instance. If you close the
1-94
Scopes group container, all docked instances of Time Scope close but the
Simulink model continues to run.
tFor more information on docking figures, see Docking Figures in the
Desktop in the MATLAB documentation.
1-95
The Spectrum Analyzer example opens, and the variables, Fs and mtlb, are
loaded into the MATLAB workspace.
1-96
2 Double-click the Signal From Workspace block. Set the block parameters
1-97
the Digital Filter Design block to filter the input signal, using the default
parameters.
1-98
1-99
Concatenate dimension = 2
The Matrix Concatenate block combines the two signals so that each
column corresponds to a different signal.
5 Double-click the Spectrum Analyzer block. The Spectrum Analyzer figure
appears. In the menu, select View > Spectrum Settings. The Spectrum
Settings panel opens.
Expand the Main options pane, if it is not already expanded.
Set Type to Power.
Select the Full frequency span check box.
Set RBW (Hz) to 5.91e-3.
Expand the Trace options pane, if it is not already expanded.
Set Units to dBW.
Set Averages to 2.
Expand the Window options pane, if it is not already expanded.
Set Overlap (%) to 50.
Set Window to Hann.
Based on these parameters, the Spectrum Analyzer uses 128 samples from
each input channel to calculate a new windowed data segment, as shown
in the following equation.
NENBW Fs
1.512 1 Hz
128 samples
RBW
11.8125 103 Hz
There are also 128 frequency points in the FFT. Also, because Overlap (%)
is set to 50, there is a buffer overlap length of 64 samples in each spectral
estimate, as shown in the following equation.
D
OL
1-100
OP
50
L
128 64 samples
100
100
Every time the scope updates the display, 64 points are plotted for each
channel. At 16 samples per frame, Spectrum Analyzer waits for 3 frames or
48 samples before displaying the first power spectral estimate.
6 Fit all the calculated data points into the display. In the Spectrum Analyzer
each of the input signals. It then displays the power spectra of the
frequency-domain signals in the Spectrum Analyzer window.
1-101
1-102
The power spectrum of the first input signal, from column one, is the yellow
line. The power spectrum of the second input signal, from column two, is
the blue line.
1-103
1-104
Change the configuration of the Array Plot properties for the display of a
distribution function.
1-105
numbins
= 201;
numtrials = 100;
r = zeros(numsamples,1);
hap3.SampleIncrement = 1/numbins;
hap3.PlotType = 'Stairs';
When the simulation has finished, the Array Plot figure displays a bell curve,
indicating a distribution that is close to normal.
1-106
1-107
Next, zoom in on the region between 0.3 and 0.7. In the Array Plot window,
click on the 0.3-second mark, and drag to the 0.7-second mark. The display
reflects this new x-axis setting, as shown in the following figure.
1-108
2
Data and Signal
Management
Learn concepts such as sample- and frame-based processing, sample rate,
delay and latency.
Sample- and Frame-Based Concepts on page 2-2
Inspect Sample and Frame Rates in Simulink on page 2-8
Convert Sample and Frame Rates in Simulink on page 2-20
Buffering and Frame-Based Processing on page 2-45
Delay and Latency on page 2-61
2-2
Create
Sample-Based
Signals
Create Frame-Based
Signals
Chirp
Constant
Constant Diagonal
Matrix
Discrete Impulse
Identity Matrix
MIDI Controls
Multiphase Clock
N-Sample Enable
Random Source
Sine Wave
UDP Receive
2-3
Sample-Based
Processing
Frame-Based
Processing
MATLAB System
objects
FrameBasedProcessing
= False
FrameBasedProcessing
= True
Simulink Blocks
Input processing
= Elements as
Input processing =
channels (sample
based)
Columns as channels
(frame based)
2-4
2-5
2-6
acquisition of a sample. The thicker blocks each represent the time elapsed
during the interrupt service routine (ISR) that reads the data from the
hardware.
In this example, the frame-based operation acquires a frame of 16 samples
between each ISR. Thus, the frame-based throughput rate is many times
higher than the sample-based alternative.
2-7
In this section...
Sample Rate and Frame Rate Concepts on page 2-8
Inspect Sample-Based Signals Using Probe Block on page 2-10
Inspect Frame-Based Signals Using Probe Block on page 2-12
Inspect Sample-Based Signals Using Color Coding on page 2-15
Inspect Frame-Based Signals Using Color Coding on page 2-16
2-8
Ts = Tf / M
More specifically, the sample periods of inputs (Tsi) and outputs (Tso) are
related to their respective frame periods by
Tsi = Tfi / Mi
Tso = Tfo / Mo
where Mi and Mo are the input and output frame sizes, respectively.
The illustration below shows a single-channel, frame-based signal with a
frame size (Mi) of 4 and a frame period (Tfi) of 1. The sample period, Tsi, is
therefore 1/4, or 0.25 second.
The frame rate of a signal is the reciprocal of the frame period. For instance,
the input frame rate would be 1 / Tfi . Similarly, the output frame rate would
be 1 / Tfo .
The sample rate of a signal is the reciprocal of the sample period. For
instance, the sample rate would be 1 / Ts .
In most cases, the sequence sample period Tsi is most important, while the
frame rate is simply a consequence of the frame size that you choose for
the signal. For a sequence with a given sample period, a larger frame size
corresponds to a slower frame rate, and vice versa.
2-9
2-10
The figure below illustrates how the Probe blocks display the sample period
of the signal before and after each upsample operation.
2-11
As displayed by the Probe blocks, the output from the Signal From
Workspace block is a sample-based signal with a sample period of 1 second.
The output from the first Upsample block has a sample period of 0.5
second, and the output from the second Upsample block has a sample
period of 0.25 second.
2-12
2-13
The figure below illustrates how the Probe blocks display the frame period
of the signal before and after each upsample operation.
As displayed by the Probe blocks, the output from the Signal From
Workspace block is a frame-based signal with a frame period of 16 seconds.
The output from the first Upsample block has a frame period of 8 seconds,
and the output from the second Upsample block has a sample period of 4
seconds.
Note that the sample rate conversion is implemented through a change in the
frame period rather than the frame size.
2-14
2 From the Display menu, point to Sample Time, and select Colors.
This selection turns on sample time color coding. Simulink now assigns
each sample rate a different color.
3 Run the model.
2-15
2-16
2 To turn on sample time color coding, from the Display menu, point to
2-17
Every signal is coded with the same color. Therefore, every signal in the
model now has the same frame rate.
2-18
For more information about sample tim color coding, see View Sample Time
Information in the Simulink documentation.
2-19
In this section...
Rate Conversion Blocks on page 2-20
Rate Conversion by Frame-Rate Adjustment on page 2-21
Rate Conversion by Frame-Size Adjustment on page 2-25
Avoid Unintended Rate Conversion on page 2-29
Frame Rebuffering Blocks on page 2-35
Buffer Signals by Preserving the Sample Period on page 2-38
Buffer Signals by Altering the Sample Period on page 2-41
2-20
Block
Library
Downsample *
Signal Operations
Block
Library
FIR Decimation *
FIR Interpolation *
Repeat *
Signal Operations
Upsample *
Signal Operations
2-21
2 From the Display menu, point to Signals & Ports, and select Signal
Dimensions.
When you run the model, the dimensions of the signals appear next to the
lines connecting the blocks.
3 Double-click the Signal From Workspace block. The Source Block
2-22
After the simulation, the model should look similar to the following figure.
2-23
Because Tfi = Mi Tsi , the input frame period, Tfi , is Tfi = 8 0.125 = 1
second. This value is displayed by the first Probe block. Therefore the input
frame rate, 1 / Tfi , is also 1 second.
The second Probe block in the model verifies that the output from the
Downsample block has a frame period, Tfo , of 2 seconds, twice the frame
period of the input. However, because the frame rate of the output, 1 Tfo ,
2-24
Tso = Tfo / Mo , is doubled to 0.25 second without any change to the frame
size. The signal dimensions in the model confirm that the frame size did
not change.
2-25
2 From the Display menu, point to Signals & Ports, and select Signal
Dimensions.
When you run the model, the dimensions of the signals appear next to the
lines connecting the blocks.
3 Double-click the Signal From Workspace block. The Source Block
2-26
After the simulation, the model should look similar to the following figure.
2-27
Because Tfi = Mi Tsi , the input frame period, Tfi , is Tfi = 8 0.125 = 1
second. This value is displayed by the first Probe block. Therefore the input
frame rate, 1 / Tfi , is also 1 second.
The Downsample block downsampled the input signal to half its original
frame size. The signal dimensions of the output of the Downsample
block confirm that the downsampled output has a frame size of 4, half
the frame size of the input. As a result, the sample period of the output,
2-28
Tso = Tfo / Mo , now has a sample period of 0.25 second. This process
occurred without any change to the frame rate ( Tfi = Tfo ).
Frequency (Hz) = 1
Sample time = 0.1
Samples per frame = 128
Based on the Sample time and the Samples per frame parameters,
the Sine Wave outputs a sinusoid with a frame period of 128*0.1 or 12.8
seconds.
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the lower Sine Wave block.
6 Set the block parameters as follows, and then click OK:
Frequency (Hz) = 2
Sample time = 0.1
Samples per frame = 128
Based on the Sample time and the Samples per frame parameters,
the Sine Wave outputs a sinusoid with a frame period of 128*0.1 or 12.8
seconds.
2-29
The model should now look similar to the following figure. Note that the
signal leaving the Magnitude FFT block is 128-by-1.
2-30
2-31
The Vector Scope block uses the input frame size (128) and period (12.8) to
deduce the original signals sample period (0.1), which allows it to correctly
display the peaks at 1 Hz and 2 Hz.
12 Double-click the Magnitude FFT block. The Function Block Parameters:
Clear the Inherit FFT length from input dimensions check box.
Set the FFT length parameter to 256.
Based on these parameters, the Magnitude FFT block zero-pads the
length-128 input frame to a length of 256 before performing the FFT.
2-32
The model should now look similar to the following figure. Note that the
signal leaving the Magnitude FFT block is 256-by-1.
2-33
In this case, based on the input frame size (256) and frame period (12.8),
the Vector Scope block incorrectly calculates the original signals sample
period to be (12.8/256) or 0.05 second. As a result, the spectral peaks
appear incorrectly at 2 Hz and 4 Hz rather than 1 Hz and 2 Hz.
The source of the error described above is unintended rate conversion.
The zero-pad operation performed by the Magnitude FFT block halves the
sample period of the sequence by appending 128 zeros to each frame. To
calculate the spectral peaks correctly, the Vector Scope block needs to know
the sample period of the original signal.
15 To correct for the unintended rate conversion, double-click the Vector
Scope block.
2-34
The Vector Scope block now accurately plots the spectral peaks at 1 Hz
and 2 Hz.
In general, when you zero-pad or overlap buffers, you are changing the sample
period of the signal. If you keep this in mind, you can anticipate and correct
problems such as unintended rate conversion.
Library
Buffer
Delay Line
2-35
Block
Library
Unbuffer
Variable Selector
Tf = MTs
However, the equation above is only true if no samples are added or deleted
from the original signal. Therefore, the equation above does not apply to
buffering operations that generate overlapping frames, that only partially
unbuffer frames, or that alter the data sequence by adding or deleting
samples.
There are two blocks in the Buffers library that can be used to change a
signals frame size without altering the signal itself:
Buffer redistributes signal samples to a larger or smaller frame size
Unbuffer unbuffers a frame-based signal to a sample-based signal
(frame size = 1)
The Buffer block preserves the signals data and sample period only when its
Buffer overlap parameter is set to 0. The output frame period, Tfo, is
Tfo =
Mo Tfi
Mi
where Tfi is the input frame period, Mi is the input frame size, and Mo is
the output frame size specified by the Output buffer size (per channel)
parameter.
2-36
Tso = Tfi / Mi
where Tfi and Mi are the period and size, respectively, of the frame-based
input.
Both the Buffer and Unbuffer blocks preserve the sample period of the
sequence in the conversion (Tso = Tsi).
Tfo = ( Mo L)Tsi
where Mo is the output frame size specified by the Output buffer size
(per channel) parameter. As a result, the new output sample period is
Tso =
( Mo L)Tsi
Mo
The Delay Line block adds duplicate samples to the sequence when the
Delay line size parameter, Mo, is greater than 1. The output and input
frame periods are the same, Tfo = Tfi = Tsi, and the new output sample
period is
2-37
Tso =
Tsi
Mo
The Variable Selector block can remove, add, and/or rearrange samples in
the input frame when Select is set to Rows. The output and input frame
periods are the same, Tfo = Tfi, and the new output sample period is
Tso =
Mi Tsi
Mo
2-38
Signal = 1:1000
Sample time = 0.125
Samples per frame = 8
Form output after final data value = Setting to zero
Based on these parameters, the Signal from Workspace block outputs a
frame-based signal with a sample period of 0.125 second. Each output
frame contains eight samples.
2-39
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Buffer block. The Function Block Parameters: Buffer
2-40
Note that the input to the Buffer block has a frame size of 8 and the output
of the block has a frame size of 16. As shown by the Probe blocks, the
rebuffering process doubles the frame period from 1 to 2 seconds.
2-41
Signal = 1:1000
Sample time = 0.125
Samples per frame = 8
Form output after final data value = Setting to zero
Based on these parameters, the Signal from Workspace block outputs a
frame-based signal with a sample period of 0.125 second. Each output
frame contains eight samples.
2-42
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Buffer block. The Function Block Parameters: Buffer
The following figure shows the model after the simulation has stopped.
2-43
Note that the input to the Buffer block has a frame size of 8 and the output
of the block has a frame size of 16. The relation for the output frame period
for the Buffer block is
Tfo = ( Mo L)Tsi
Tfo is (16-4)*0.125, or 1.5 seconds, as confirmed by the second Probe block.
The sample period of the signal at the output of the Buffer block is no
longer 0.125 second. It is now Tso = Tfo / Mo = 1.5 / 16 = 0.0938 second.
Thus, both the signals data and the signals sample period have been
altered by the buffering operation.
2-44
In this section...
Frame Status on page 2-45
Buffer Sample-Based Signals into Frame-Based Signals on page 2-45
Buffer Sample-Based Signals into Frame-Based Signals with Overlap
on page 2-49
Buffer Frame-Based Signals into Other Frame-Based Signals on page 2-53
Buffer Delay and Initial Conditions on page 2-56
Unbuffer Frame-Based Signals into Sample-Based Signals on page 2-57
Frame Status
The frame status of a signal refers to whether the signal is sample based or
frame based. In a Simulink model, the frame status is symbolized by a single
line ,, for a sample-based signal and a double line, for a frame-based
signal. One way to convert a sample-based signal to a frame-based signal
is by using the Buffer block. You can convert a frame-based signal to a
sample-based signal using the Unbuffer block. To change the frame status of
a signal without performing a buffering operation, use the Frame Conversion
block in the Signal Attributes library.
2-45
2-46
Signal = [1:10;-1:-1:-10]'
Sample time = 1
Samples per frame = 1
Form output after final data value = Setting to zero
Based on these parameters, the Signal from Workspace block outputs a
sample-based signal with a sample period of 1 second. Because you set the
Samples per frame parameter setting to 1, the Signal From Workspace
block outputs one two-channel sample at each sample time.
2-47
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Buffer block. The Function Block Parameters: Buffer
Note that the input to the Buffer block is sample based (represented as a
single line) while the output is frame-based (represented by a double line).
The figure below is a graphical interpretation of the model behavior during
simulation.
[4 -4]
[3 -3]
[2 -2]
[1 -1]
t=3
t=2
t=1
t=0
1
2
3
4
-1
-2
-3
-4
Note Alternatively, you can set the Samples per frame parameter of the
Signal From Workspace block to 4 and create the same frame-based signal
shown above without using a Buffer block. The Signal From Workspace
block performs the buffering internally, in order to output a two-channel
frame-based signal.
2-48
2-49
Signal = sp_examples_src
Sample time = 1
2-50
Note that the input to the Buffer block is sample based (represented as a
single line) while the output is frame based (represented by a double line).
The following figure is a graphical interpretation of the models behavior
during simulation.
2-51
2-52
0
0
0
0
1
1
1
0
0
0
1
1
1
0
0
0
0
0
0
0
0
5
5
5
5
5
5
5
5
5
0
0
0
0
0
0
0
0
-1
-2
-2
-3
-4
-4
-5
-6
-6
0
0
0
0
Notice that the inputs do not begin appearing at the output until the fifth
row, the second row of the second frame. This is due to the blocks latency.
See Excess Algorithmic Delay (Tasking Latency) on page 2-70 for general
information about algorithmic delay. For instructions on how to calculate
buffering delay, see Buffer Delay and Initial Conditions on page 2-56.
2-53
Signal = sp_examples_src
2-54
Sample time = 1
Samples per frame = 4
Based on these parameters, the Signal From Workspace block outputs a
two-channel, frame-based signal with a sample period of 1 second and a
frame size of 4.
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Buffer block. The Function Block Parameters: Buffer
Note that the inputs do not begin appearing at the output until the last row
of the third output matrix. This is due to the blocks latency.
2-55
See Excess Algorithmic Delay (Tasking Latency) on page 2-70 for general
information about algorithmic delay. For instructions on how to calculate
buffering delay, and see Buffer Delay and Initial Conditions on page 2-56.
This result agrees with the blocks output in that example. Notice that this
model was simulated in Simulink multitasking mode.
For more information about delay, see Excess Algorithmic Delay (Tasking
Latency) on page 2-70. For delay information about a specific block, see the
Latency section of the block reference page. For more information about the
rebuffer_delay function, see rebuffer_delay.
2-56
The sample period of the sample-based output, Tso, is related to the input
frame period, Tfi, by the input frame size, Mi.
Tso = Tfi / Mi
The Unbuffer block always preserves the signals sample period (Tso = Tsi).
See Convert Sample and Frame Rates in Simulink on page 2-20 for more
information about rate conversions.
2-57
Signal = [1:10;-1:-1:-10]'
Sample time = 1
Samples per frame = 4
2-58
1
2
3
4
-1
-2
-3
-4
[4 -4]
[3 -3]
[2 -2]
[1 -1]
t=7
t=6
t=5
t=4
Note The Unbuffer block generates initial conditions not shown in the
figure below with the value specified by the Initial conditions parameter.
See the Unbuffer reference page for information about the number of initial
conditions that appear in the output.
8 At the MATLAB command prompt, type sp_examples_yout.
2-59
sp_examples_yout(:,:,1) =
0
sp_examples_yout(:,:,2) =
0
sp_examples_yout(:,:,3) =
0
sp_examples_yout(:,:,4) =
0
sp_examples_yout(:,:,5) =
1
-1
sp_examples_yout(:,:,6) =
2
-2
sp_examples_yout(:,:,7) =
3
-3
2-60
In this section...
Computational Delay on page 2-61
Algorithmic Delay on page 2-63
Zero Algorithmic Delay on page 2-63
Basic Algorithmic Delay on page 2-66
Excess Algorithmic Delay (Tasking Latency) on page 2-70
Predict Tasking Latency on page 2-72
Computational Delay
The computational delay of a block or subsystem is related to the number
of operations involved in executing that block or subsystem. For example,
an FFT block operating on a 256-sample input requires Simulink software
to perform a certain number of multiplications for each input frame. The
actual amount of time that these operations consume depends heavily on the
performance of both the computer hardware and underlying software layers,
such as the MATLAB environment and the operating system. Therefore,
computational delay for a particular model can vary from one computer
platform to another.
The simulation time represented on a models status bar, which can
be accessed via the Simulink Digital Clock block, does not provide any
information about computational delay. For example, according to the
Simulink timer, the FFT mentioned above executes instantaneously, with
no delay whatsoever. An input to the FFT block at simulation time t=25.0
is processed and output at simulation time t=25.0, regardless of the number
2-61
2-62
You cannot interact with the simulation (to tune parameters, for
instance).
You must press Ctrl+C to stop the simulation, or specify start and
stop times.
Algorithmic Delay
Algorithmic delay is delay that is intrinsic to the algorithm of a block or
subsystem and is independent of CPU speed. In this guide, the algorithmic
delay of a block is referred to simply as the blocks delay. It is generally
expressed in terms of the number of samples by which a blocks output lags
behind the corresponding input. This delay is directly related to the time
elapsed on the Simulink timer during that blocks execution.
The algorithmic delay of a particular block may depend on both the block
parameter settings and the general Simulink settings. To simplify matters, it
is helpful to categorize a blocks delay using the following categories:
Zero Algorithmic Delay on page 2-63
Basic Algorithmic Delay on page 2-66
Excess Algorithmic Delay (Tasking Latency) on page 2-70
The following topics explain the different categories of delay, and how
the simulation and parameter settings can affect the level of delay that a
particular block experiences.
2-63
Signal = 1:100
Sample time = 1/4
Samples per frame = 4
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Frame Conversion block. The Function Block
2-64
The model prepends the current value of the Simulink timer output from
the Digital Clock block to each output frame. The Frame Conversion block
converts the frame-based signal to a sample-based signal so that the output
in the MATLAB Command Window is more easily readable.
The Signal From Workspace block generates a new frame containing four
samples once every second (Tfo = *4). The first few output frames are:
(t=0)
(t=1)
(t=2)
(t=3)
(t=4)
[ 1 2 3 4]'
[ 5 6 7 8]'
[ 9 10 11 12]'
[13 14 15 16]'
[17 18 19 20]'
0.0333
0.0287
0.0202
0.0154
0.0124
0.0103
0.0667
0.0345
0.0224
0.0165
0.0131
0.0108
0.1000
0.0402
0.0247
0.0177
0.0138
0.0113
0.1333
0.0460
0.0269
0.0189
0.0146
0.0118
The first column of ans is the Simulink time provided by the Digital Clock
block. You can see that the squared 2-norm of the first input,
[1 2 3 4]' ./ sum([1 2 3 4]'.^2)
2-65
appears in the first row of the output (at time t=0), the same time step that
the input was received by the block. This indicates that the Normalization
block has zero algorithmic delay.
2-66
Signal = 1:100
Sample time = 1
Samples per frame = 1
4 Save these parameters and close the dialog box by clicking OK.
5 Double-click the Constant block. The Source Block Parameters:
Constant value = 3
Interpret vector parameters as 1D = Clear this check box
2-67
2-68
-1
-1
-1
1
2
3
The first column is the Simulink time provided by the Digital Clock block.
The second column is the delayed input. As expected, the input to the block
at t=0 is delayed three samples and appears as the fourth output sample,
at t=3. You can also see that the first three outputs from the Variable
2-69
Integer Delay block inherit the value of the blocks Initial conditions
parameter, -1. This period of time, from the start of the simulation until
the first input is propagated to the output, is sometimes called the initial
delay of the block.
Many DSP System Toolbox blocks have some degree of fixed or adjustable
algorithmic delay. These include any blocks whose algorithms rely on delay
or storage elements, such as filters or buffers. Often, but not always, such
blocks provide an Initial conditions parameter that allows you to specify
the output values generated by the block during the initial delay. In other
cases, the initial conditions are internally set to 0.
Consult the block reference pages for the delay characteristics of specific
DSP System Toolbox blocks.
2-70
Multitasking
To select a mode, from the Simulation menu, select Model Configuration
Parameters. In the Select pane, click Solver. From the Type list, select
Fixed-step. From the Tasking mode for periodic sample times list,
choose SingleTasking or MultiTasking. If, from the Tasking mode
for periodic sample times list you select Auto, the simulation runs in
single-tasking mode if the model is single-rate, or multitasking mode if the
model is multirate.
Note Many multirate blocks have reduced latency in the Simulink
single-tasking mode. Check the Latency section of a multirate blocks
reference page for details. Also see Scheduling in the Simulink Coder Users
Guide.
2-71
2-72
Signal = 1:100
2-73
Upsample factor, L = 4
Sample offset (0 to L-1) = 0
Input processing = Columns as channels (frame based)
Rate options = Allow multirate processing
Initial condition = -1
The Rate options parameter makes the model multirate, since the input
and output frame rates will not be equal.
9 Double-click the Digital Clock block. The Source Block Parameters:
2-74
The model prepends the current value of the Simulink timer, from the
Digital Clock block, to each output frame. The Frame Conversion block
converts the frame-based signal into a sample-based signal so that the
output in the MATLAB Command Window is easily readable.
In the example, the Signal From Workspace block generates a new frame
containing four samples once every second (Tfo = *4). The first few output
frames are:
(t=0)
(t=1)
(t=2)
(t=3)
(t=4)
[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]
2-75
Probe blocks in the model, which show a decrease in the frame period from
Tfi = 1 to Tfo = 0.25.
14 At the MATLAB command prompt, type squeeze(dsp_examples_yout)'.
The output from the simulation is displayed in a matrix format. The first
few samples of the result, ans, are:
2-76
17 From the Tasking mode for periodic sample times list, select
SingleTasking.
18 Run the model.
2-77
2-78
3
Filter Analysis, Design, and
Implementation
Design a Filter in Fdesign Process Overview on page 3-2
Design a Filter in the Filterbuilder GUI on page 3-11
Use FDATool with DSP System Toolbox Software on page 3-16
Digital Frequency Transformations on page 3-88
Digital Filter Design Block on page 3-123
Filter Realization Wizard on page 3-134
Digital Filter Block on page 3-147
Analog Filter Design Block on page 3-159
3-2
The first four steps of the filter design process relate to the filter Specifications
Object, while the last two steps involve the filter Implementation Object. Both
of these objects are discussed in more detail in the following sections. Step 5
- the design of the filter, is the transition step from the filter Specifications
Object to the Implementation object. The analysis and verification step is
3-3
completely optional. It provides methods for the filter designer to ensure that
the filter complies with all design criteria. Depending on the results of this
verification, you can loop back to steps 3 and 4, to either choose a different
algorithm, or to customize the current one. You may also wish to go back to
steps 3 or 4 after you filter the input data with the designed filter (step 7),
and find that you wish to tweak the filter or change it further.
The diagram shows the help command for each step. Enter the help line at the
MATLAB command prompt to receive instructions and further documentation
links for the particular step. Not all of the steps have to be executed explicitly.
For example, you could go from step 1 directly to step 5, and the interim three
steps are done for you by the software.
The following are the details for each of the steps shown above.
Select a Response
If you type:
help fdesign/responses
at the MATLAB command prompt, you see a list of all available filter
responses. The responses marked with an asterisk require the DSP System
Toolbox.
You must select a response to initiate the filter. In this example, a bandpass
filter Specifications Object is created by typing the following:
d = fdesign.bandpass
Select a Specification
A specification is an array of design parameters for a given filter. The
specification is a property of the Specifications Object.
Note A specification is not the same as the Specifications Object. A
Specifications Object contains a specification as one of its properties.
3-4
The set command can be used to select one of the available specifications as
follows:
>> d = fdesign.lowpass; % step 1
>> % step 2: get a list of available specifications
>> set (d, 'specification')
3-5
ans =
'Fp,Fst,Ap,Ast'
'N,F3dB'
'N,F3dB,Ap'
'N,F3dB,Ap,Ast'
'N,F3dB,Ast'
'N,F3dB,Fst'
'N,Fc'
'N,Fc,Ap,Ast'
'N,Fp,Ap'
'N,Fp,Ap,Ast'
'N,Fp,F3dB'
'N,Fp,Fst'
'N,Fp,Fst,Ap'
'N,Fp,Fst,Ast'
'N,Fst,Ap,Ast'
'N,Fst,Ast'
'Nb,Na,Fp,Fst'
>> %step 2: set the required specification
>> set (d, 'specification', 'N,Fc')
If you do not perform this step explicitly, fdesign returns the default
specification for the response you chose in Select a Response on page 3-4, and
provides default values for all design parameters included in the specification.
Select an Algorithm
The availability of algorithms depends the chosen filter response, the design
parameters, and the availability of the DSP System Toolbox. In other words,
for the same lowpass filter, changing the specification string also changes the
available algorithms. In the following example, for a lowpass filter and a
specification of 'N, Fc', only one algorithm is availablewindow.
>> %step 2: set the required specification
>> set (d, 'specification', 'N,Fc')
>> designmethods (d) %step3: get available algorithms
3-6
window
butter
cheby1
cheby2
ellip
equiripple
kaiserwin
If the user additionally has the DSP System Toolbox installed, the number of
available algorithms for this response and specification string increases:
>>set(d,'specification','Fp,Fst,Ap,Ast')
>>designmethods(d)
butter
cheby1
cheby2
ellip
equiripple
ifir
kaiserwin
multistage
3-7
The user chooses a particular algorithm and implements the filter with the
design function.
>>Hd=design(d,'butter');
The preceding code actually creates the filter, where Hd is the filter
Implementation Object. This concept is discussed further in the next step.
If you do not perform this step explicitly, design automatically selects the
optimum algorithm for the chosen response and specification.
where Hd is the Filter Object and d is the Specifications Object. This code
creates a filter without specifying the algorithm. When the algorithm is not
specified, the software selects the best available one.
3-8
To apply the algorithm chosen in Select an Algorithm on page 3-6, use the
same design command, but specify the Butterworth algorithm as follows:
>> Hd = design(d, 'butter');
This help command describes not only the options for the design command
itself, but also options that pertain to the method or the algorithm. If you
are customizing the algorithm, you apply these options in this step. In the
following example, you design a bandpass filter, and then modify the filter
structure:
>> Hd = design(d, 'butter', 'filterstructure', 'df2sos')
f =
FilterStructure:
Arithmetic:
sosMatrix:
ScaleValues:
PersistentMemory:
The filter design step, just like the first task of choosing a response, must be
performed explicitly. A Filter Object is created only when design is called.
Design Analysis
After the filter is designed you may wish to analyze it to determine if the filter
satisfies the design criteria. Filter analysis is broken into three main sections:
Frequency domain analysis Includes the magnitude response, group
delay, and pole-zero plots.
Time domain analysis Includes impulse and step response
Implementation analysis Includes quantization noise and cost
3-9
This step is never automatically performed for you. To filter your data, you
must explicitly execute this step. To understand how the filtering commands
work, type:
>> help dfilt/filter
Note If you have Simulink, you have the option of exporting this filter
to a Simulink block using the realizemdl command. To get help on this
command, type:
>> help realizemdl
3-10
Introduction to Filterbuilder
The filterbuilder function provides a graphical interface to the
fdesign object-oriented filter design paradigm and is intended to reduce
development time during the filter design process. filterbuilder uses a
specification-centered approach to find the best filter for the desired response.
Note filterbuilder requires the Signal Processing Toolbox. The
functionality of filterbuilder is greatly expanded by the DSP System
Toolbox. Some of the features described or displayed below are only available
if the DSP System Toolbox is installed. You may verify your installation by
typing ver at the command prompt.
3-11
performance criteria. The following are the details of each of the steps for
designing a filter with filterbuilder.
Select a Response
When you open the filterbuilder tool by typing:
filterbuilder
3-12
Select a Specification
To choose the specification for the bandpass filter, you can begin by selecting
an Impulse Response, Order Mode, and Filter Type in the Filter
Specifications frame of the Main Pane. You can further specify the
response of your filter by setting frequency and magnitude specifications in
the appropriate frames on the Main Pane.
Note Frequency, Magnitude, and Algorithm specifications are
interdependent and may change based upon your Filter Specifications
selections. When choosing specifications for your filter, select your Filter
Specifications first and work your way down the dialog box- this approach
ensures that the best settings for dependent specifications display as available
in the dialog box.
Select an Algorithm
The algorithms available for your filter depend upon the filter response and
design parameters you have selected in the previous steps. For example, in the
case of a bandpass filter, if the impulse response selected is IIR and the Order
Mode field is set toMinimum, the design methods available are Butterworth,
Chebyshev type I or II, or Elliptic, whereas if the Order Mode field is set
to Specify, the design method available is IIR least p-norm.
3-13
3-14
Tip If you have Simulink, you have the option of exporting this filter to
a Simulink block using the realizemdl command. To get help on this
command, type:
>> help realizemdl
3-15
3-16
Design advanced filters that Signal Processing Toolbox software does not
provide the design tools to develop.
View Simulink models of the filter structures available in the toolbox.
Quantize double-precision filters you design in this GUI using the design
mode.
Quantize double-precision filters you import into this GUI using the import
mode.
Analyze quantized filters.
Scale second-order section filters.
Select the quantization settings for the properties of the quantized filter
displayed by the tool:
Input/output control how the filter processes input and output data
Filter Internals specify how the arithmetic for the filter behaves
3-17
As you select a response type, the options in the right panes in FDATool
change to let you set the values that define your filter. You also see that the
analysis area includes a diagram (called a design mask) that describes the
options for the filter response you choose.
By reviewing the mask you can see how the options are defined and how
to use them. While this is usually straightforward for lowpass or highpass
filter responses, setting the options for the arbitrary response types or the
peaking/notching filters is more complicated. Having the masks leads you
to your result more easily.
Changing the filter design method changes the available response type
options. Similarly, the response type you select may change the filter design
methods you can choose.
list.
3 For the Frequency Specifications, set Units to Hz and Fs, the full scale
frequency, to 1000.
4 Set the location of the center of the notch, in either normalized frequency
3-18
as 1.
7 Click Design Filter.
FDATool computes the filter coefficients and plots the filter magnitude
response in the analysis area for you to review.
When you design a single notch filter, you do not have the option of setting
the filter order the Filter Order options are disabled.
Your filter should look about like this:
3-19
For more information about a design method, refer to the online Help system.
For instance, to get further information about the Q setting for the notch
filter in FDATool, enter
doc iirnotch
at the command line. This opens the Help browser and displays the reference
page for function iirnotch.
3-20
3-21
The Filter arithmetic option lets you quantize filters and investigate the
effects of changing quantization settings. To enable the quantization settings
in FDATool, select Fixed-point from the Filter Arithmetic.
The quantization options appear in the lower panel of FDATool. You see tabs
that access various sets of options for quantizing your filter.
You use the following tabs in the dialog box to perform tasks related to
quantizing filters in FDATool:
Coefficients provides access the settings for defining the coefficient
quantization. This is the default active panel when you switch FDATool
to quantization mode without a quantized filter in the tool. When you
3-22
import a fixed-point filter into FDATool, this is the active pane when you
switch to quantization mode.
Input/Output switches FDATool to the options for quantizing the inputs
and outputs for your filter.
Filter Internals lets you set a variety of options for the arithmetic your
filter performs, such as how the filter handles the results of multiplication
operations or how the filter uses the accumulator.
Apply applies changes you make to the quantization parameters for
your filter.
3-23
When you click Set Quantization Parameters, and then change Filter
arithmetic to Fixed-point, the quantized filter panel opens in FDATool,
with the coefficient quantization options set to default values.
Coefficients Options
To let you set the properties for the filter coefficients that make up your
quantized filter, FDATool lists options for numerator word length (and
denominator word length if you have an IIR filter). The following table lists
each coefficients option and a short description of what the option setting
does in the filter.
3-24
Option Name
When Used
Description
FIR/IIR
FIR/IIR
IIR filters
Option Name
When Used
Description
IIR filters
Best-precision fraction
lengths
All filters
Use unsigned
representation
All filters
All filters
3-25
Input/Output Options
The options that specify how the quantized filter uses input and output values
are listed in the table below.
3-26
Option Name
When Used
Description
All filters
All filters
All filters
All filters
Avoid overflow
All filters
Output fraction
length
All filters
All filters
Option Name
When Used
Description
Avoid overflow
Avoid overflow
Option
Equivalent Filter
Property (Using
Wildcard *)
Round towards
RoundMode
Description
Sets the mode the filter uses to quantize
numeric values when the values lie
between representable values for the
data format (word and fraction lengths).
Choose from one of:
ceil - Round toward positive infinity.
convergent - Round to the closest
representable integer. Ties round to
the nearest even stored integer. This
3-27
Option
Equivalent Filter
Property (Using
Wildcard *)
Description
is the least biased of the methods
available in this software.
fix/zero - Round toward zero.
floor - Round toward negative
infinity.
nearest - Round toward nearest. Ties
round toward positive infinity.
round - Round toward nearest.
Ties round toward negative infinity
for negative numbers, and toward
positive infinity for positive numbers.
Overflow Mode
OverflowMode
3-28
Product Mode
ProductMode
*ProdWordLength
Option
Equivalent Filter
Property (Using
Wildcard *)
NumProdFracLength
DenProdFracLength
Accum. mode
AccumMode
*AccumWordLength
NumAccumFracLength
DenAccumFracLength
CastBeforeSum
Description
3-29
Option
Equivalent Filter
Property (Using
Wildcard *)
*StateWordLength
Avoid overflow
None
*StateFracLength
Description
Note When you apply changes to the values in the Filter Internals pane, the
plots for the Magnitude response estimate and Round-off noise power
spectrum analyses update to reflect those changes. Other types of analyses
are not affected by changes to the values in the Filter Internals pane.
arithmetic.
3-30
When you select one of the optional arithmetic settings, FDATool quantizes
the current filter according to the settings of the options in the Set
Quantization Parameter panes, and changes the information displayed in
the analysis area to show quantized filter data.
3 In the quantization panes, set the options for your filter. Set options for
Parameters panel.
3 Review and select property settings for the filter quantization:
3-31
3-32
Analysis Parameter
Default
Setting
Number of Points
512
Frequency Range
0 to Fs/2
Frequency Units
Hz
Sampling Frequency
48000
Description
Analysis Parameter
Default
Setting
Frequency Scale
dB
Normalized
Frequency
Off
Description
After your first analysis run ends, open the Analysis Parameters dialog
box and adjust your settings appropriately, such as changing the number of
trials or number of points.
To open the Analysis Parameters dialog box, use either of the next
procedures when you have a quantized filter in FDATool:
Select Analysis > Analysis Parameters from the menu bar
Right-click in the filter analysis area and select Analysis Parameters
from the context menu
Whichever option you choose opens the dialog box. Notice that the settings
for the options reflect the defaults.
Noise Method Applied to a Filter. To demonstrate the magnitude response
estimate method, start by creating a quantized filter. For this example, use
FDATool to design a sixth-order Butterworth IIR filter.
To Use Noise-Based Analysis in FDATool.
1 Enter fdatool at the MATLAB prompt to launch FDATool.
2 Under Response Type, select Highpass.
3 Select IIR in Design Method. Then select Butterworth.
4 To set the filter order to 6, select Specify order under Filter Order.
3-33
settings, click
Now the analysis areas shows the magnitude response for both filters
your original filter and the fixed-point arithmetic version.
8 Finally, to use noise-based estimation on your quantized filter, select
In the above figure you see the magnitude response as estimated by the
analysis method.
3-34
View the Noise Power Spectrum. When you use the noise method to
estimate the magnitude response of a filter, FDATool simulates and applies
a spectrum of noise values to test your filter response. While the simulated
noise is essentially white, you might want to see the actual spectrum that
FDATool used to test your filter.
From the Analysis menu bar option, select Round-off Noise Power
Spectrum. In the analysis area in FDATool, you see the spectrum of the
noise used to estimate the filter response. The details of the noise spectrum,
such as the range and number of data points, appear in the Analysis
Parameters dialog box.
For more information, refer to McClellan, et al., Computer-Based Exercises
for Signal Processing Using MATLAB 5, Prentice-Hall, 1998. See Project 5:
Quantization Noise in Digital Filters, page 231.
Change Your Noise Analysis Parameters. In Noise Method Applied
to a Filter on page 3-33, you used synthetic white noise to estimate the
magnitude response for a fixed-point highpass Butterworth filter. Since you
ran the estimate only once in FDATool, your noise analysis used the default
analysis parameters settings shown in Analyze Filters with the Magnitude
Response Estimate Method on page 3-32.
To change the settings, follow these steps after the first time you use the
noise estimate on your quantized filter.
1 With the results from running the noise estimating method displayed in
3-35
test without closing the dialog box. When you want to try many different
settings for the noise-based analysis, this is a useful shortcut.
3-36
dfilt.calattice
dfilt.calatticepc
Direct Form Antisymmetric FIR Filter Structure (Any Order)
Starting from any quantized filter, you can convert to one of the following
representation:
Direct form I
Direct form II
Direct form I transposed
Direct form II transposed
Lattice ARMA
Additionally, FDATool lets you do the following conversions:
Minimum phase FIR filter to Lattice MA minimum phase
Maximum phase FIR filter to Lattice MA maximum phase
Allpass filters to Lattice allpass
Refer to FilterStructure for details about each of these structures.
3-37
3-38
Parameter
Scale
No Overflow High
SNR slider
Maximum
Numerator
Numerator
Constraint
3-39
Parameter
Overflow Mode
Scale Value
Constraint
Revert to Original
Filter
3-40
3 In Design Method, select IIR and Elliptic from the IIR design methods
list.
4 Select Minimum Order for the filter.
5 Switch the frequency units by choosing Normalized(0 to 1) from the
Units list.
6 To set the passband specifications, enter 0.45 for wpass and 0.55 for
After FDATool finishes designing the filter, you see the following plot and
settings in the tool.
3-41
You kept the Options setting for Match exactly as both, meaning the
filter design matches the specification for the passband and the stopband.
8 To switch to scaling the filter, select Edit > Reorder and Scale
3-42
Now try scaling the filter in a few different ways. First scale the filter to
maximize the SNR.
1 Return to the Reordering and Scaling Second-Order Sections dialog
box and select None for Reordering in the left pane. This prevents
FDATool from reordering the filter sections when you rescale the filter.
2 Move the No OverflowHigh SNR slider from No Overflow to High
SNR.
3 Click Apply to scale the filter and leave the dialog box open.
3-43
In this dialog box, the left-hand side contains options for reordering SOS
filters. On the right you see the scaling options. These are independent
reordering your filter does not require scaling (note the Scale option) and
scaling does not require that you reorder your filter (note the None option
under Reordering). For more about scaling SOS filters, refer to Scale
Second-Order Section Filters on page 3-38 and to scale in the reference
section.
Reordering SOS filters involves using the options in the Reordering and
Scaling of Second-Order Sections dialog box. The following table lists
each reorder option and provides a description of what the option does.
3-44
Control Option
Description
Auto
None
Least selective
section to most
selective section
Most selective
section to least
selective section
Custom reordering
Numerator Order
Use Numerator
Order
3-45
Control Option
Description
Specify
Use Numerator
Order
Specify
Revert to Original
Filter
3-46
section.
2 To prevent filter scaling at the same time, clear Scale in Scaling.
3 In FDATool, select View > SOS View Settings from the menu bar so you
box, click Apply to reorder your filter according to the Qs of the filter
sections, and keep the dialog box open. In response, FDATool presents
the responses for each filter section (there should be five sections) in the
analysis area.
3-47
In the next two figures you can compare the ordering of the sections of
your filter. In the first figure, your original filter sections appear. In the
second figure, the sections have been rearranged from least selective to
most selective.
You see what reordering does, although the result is a bit subtle. Now try
custom reordering the sections of your filter or using the most selective to
least selective reordering option.
3-48
3-49
By default, SOS View shows the overall response of SOS filters. Options in
the SOS View dialog box let you change the display. This table lists all the
options and describes the effects of each.
Option
Description
Overall Filter
Individual sections
Cumulative sections
3-50
Option
Description
User defined
Use secondary-scaling
points
3-51
2 Create a lowpass SOS filter using the Butterworth design method. Specify
the filter order to be 6. Using a low order filter makes seeing the sections
more clear.
3 Design your new filter by clicking Design Filter.
FDATool design your filter and show you the magnitude response in the
analysis area. In Current Filter Information you see the specifications for
your filter. You should have a sixth-order Direct-Form II, Second-Order
Sections filter with three sections.
4 To enable SOS View, select View > SOS View from the menu bar.
By default the analysis area in FDATool shows the overall filter response,
not the individual filter section responses. This dialog box lets you change
the display configuration to see the sections.
5 To see the magnitude responses for each filter section, select Individual
sections.
6 Click Apply to update FDATool to display the responses for each filter
section. The analysis area changes to show you something like the
following figure.
3-52
7 To define your own display of the sections, you use the User defined
option and enter a vector of section indices to display. Now you see a
display of the first section response, and the cumulative first, second, and
third sections response:
Select User defined to enable the text entry box in the dialog box.
Enter the cell array {1,1:3} to specify that FDATool should display the
response of the first section and the cumulative response of the first
three sections of the filter.
8 To apply your new SOS View selection, click Apply or OK (which closes
3-53
3-54
Direct form II
Direct form I transposed
Direct form II transposed
Direct form symmetric FIR
Direct form antisymmetric FIR
Lattice allpass
Lattice AR
Lattice MA minimum phase
Lattice MA maximum phase
Lattice ARMA
Lattice coupled-allpass
Lattice coupled-allpass power complementary
choose the Import Filter from Workspace icon in the side panel:
.
In the lower region of FDATool, the Design Filter pane becomes Import
Filter, and options appear for importing quantized filters, as shown.
3-55
FDATool checks your workspace for the specified filter. It imports the filter
if it finds it, displaying the magnitude response for the filter in the analysis
area. If it cannot find the filter it returns an FDATool Error dialog box.
3-56
Note If, during any FDATool session, you switch to quantization mode
and create a fixed-point filter, FDATool remains in quantization mode. If
you import a double-precision filter, FDATool automatically quantizes your
imported filter applying the most recent quantization parameters.
When you check the current filter information for your imported filter, it
will indicate that the filter is Source: imported (quantized) even though
you did not import a quantized filter.
3-57
Do not try to export the filter to a variable name that exists in your
workspace without selecting Overwrite existing variables, in the
previous step. If you do so, FDATool stops the export operation. The tool
returns a warning that the variable you specified as the quantized filter
name already exists in the workspace.
To continue to export the filter to the existing variable, click OK to
dismiss the warning.
Then select the Overwrite existing variables check box and click
Export.
Getting Filter Coefficients After Exporting. To extract the filter
coefficients from your quantized filter after you export the filter to MATLAB,
use the celldisp function in MATLAB. For example, create a quantized filter
in FDATool, and export the filter as Hq. To extract the filter coefficients for
Hq, use
celldisp(Hq.referencecoefficients)
which returns the cell array containing the filter reference coefficients, or
celldisp(Hq.quantizedcoefficients
3-58
the filter without closing the Export dialog box. Clicking Apply lets
you export your quantized filter to more than one name without leaving
the Export dialog box.
The Export Filter Coefficients to Text-file dialog box appears. This is
the standard Microsoft Windows save file dialog box.
4 Choose or enter a folder and filename for the text file, and click OK.
FDATool exports your quantized filter as a text file with the name you
provided, and the MATLAB editor opens, displaying the file for editing.
Export Filter Coefficients as a MAT-File. To save your quantized filter as a
MAT-file, follow these steps:
1 Select Export from the File menu.
2 Select MAT-file under Export to.
3 Assign a variable name for the filter.
4 Click OK to export the filter and close the dialog box. Click Apply to export
the filter without closing the Export dialog box. Clicking Apply lets
you export your quantized filter to more than one name without leaving
the Export dialog box.
The Export Filter Coefficients to MAT-file dialog box appears. This
dialog box is the standard Microsoft Windows save file dialog box.
5 Choose or enter a folder and filename for the text file, and click OK.
3-59
in FDATool.
2 In the Import Filter From XILINX Coefficient (.COE) File dialog box,
3-60
3-61
Your options for Original filter type refer to the type of your current filter
to transform. If you select lowpass, you can transform your lowpass filter
to another lowpass filter or to a highpass filter, or to numerous other filter
formats, real and complex.
Note When your original filter is an FIR filter, both the FIR and IIR
transformed filter type options appear on the Transformed filter type list.
Both options remain active because you can apply the IIR transforms to an
FIR filter. If your source is as IIR filter, only the IIR transformed filter
options show on the list.
3-62
Lowpass
Highpass
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
When you select Lowpass with an FIR filter, your transformed filter
type can be
Lowpass
Lowpass (FIR)
Highpass
Highpass (FIR) narrowband
Highpass (FIR) wideband
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
In the following table you see each available original filter type and all the
types of filter to which you can transform your original.
Original Filter
Lowpass FIR
Lowpass
Lowpass (FIR)
Highpass
Highpass (FIR) narrowband
Highpass (FIR) wideband
Bandpass
Bandstop
Multiband
3-63
Original Filter
Lowpass IIR
Lowpass
Highpass
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
Highpass FIR
Lowpass
Lowpass (FIR) narrowband
Lowpass (FIR) wideband
Highpass (FIR)
Highpass
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
3-64
Original Filter
Highpass IIR
Lowpass
Highpass
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
Bandpass FIR
Bandpass
Bandpass (FIR)
Bandpass IIR
Bandpass
Bandstop FIR
Bandstop
Bandstop (FIR)
Bandstop IIR
Bandstop
Note also that the transform options change depending on whether your
original filter is FIR or IIR. Starting from an FIR filter, you can transform
to IIR or FIR forms. With an IIR original filter, you are limited to IIR target
filters.
After selecting your response type, use Frequency point to transform to
specify the magnitude response point in your original filter to transfer to
your target filter. Your target filter inherits the performance features of your
original filter, such as passband ripple, while changing to the new response
form.
For more information about transforming filters, refer to Frequency
Transformations for Real Filters on page 3-96 and Frequency
Transformations for Complex Filters on page 3-110.
3-65
3-66
Bandpass
Bandstop
Multiband
Bandpass (complex)
Bandstop (complex)
Multiband (complex)
Not all types of transformed filters are available for all filter types on the
Original filter types list. You can transform bandpass filters only to
bandpass filters. Or bandstop filters to bandstop filters. Or IIR filters to
IIR filters.
For more information about transforming filters, refer to Frequency
Transformations for Real Filters on page 3-96 and Frequency
Transformations for Complex Filters on page 3-110.
3-67
3 From the Original filter type list, select the response form of the filter
transform. Notice that the value you enter must be in KHz; for example,
enter 0.1 for 100 Hz or 1.5 for 1500 Hz.
5 From the Transformed filter type list, select the type of filter you want
to transform to.
Your filter type selection changes the options here.
When you pick a lowpass or highpass filter type, you enter one value in
Specify desired frequency location.
When you pick a bandpass or bandstop filter type, you enter two values
one in Specify desired low frequency location and one in Specify
desired high frequency location. Your values define the edges of
the passband or stopband.
When you pick a multiband filter type, you enter values as elements in
a vector in Specify a vector of desired frequency locations one
element for each desired location. Your values define the edges of the
passbands and stopbands.
After you click Transform Filter, FDATool transforms your filter,
displays the magnitude response of your new filter, and updates the
Current Filter Information to show you that your filter has been
transformed. In the filter information, the Source is Transformed.
For example, the figure shown here includes the magnitude response
curves for two filters. The original filter is a lowpass filter with rolloff
between 0.2 and 0.25. The transformed filter is a lowpass filter with
rolloff region between 0.8 and 0.85.
3-68
Magnitude Response
20
Magnitude (dB)
20
40
60
80
100
0.1
0.2
0.3
0.4
0.5
0.6
Normalized Frequency ( rad/sample)
0.7
0.8
0.9
3-69
Magnitude Response
20
Magnitude (dB)
20
40
60
80
100
120
0.1
0.2
0.3
0.4
0.5
0.6
Normalized Frequency ( rad/sample)
0.7
0.8
0.9
3-70
Introduction
Not only can you design multirate filters from the MATLAB command prompt,
FDATool provides the same design capability in a graphical user interface
tool. By starting FDATool and switching to the multirate filter design mode
you have access to all of the multirate design capabilities in the toolbox
decimators, interpolators, and fractional rate changing filters, among others.
3-71
When the current filter in FDATool is not an FIR filter, the multirate filter
design panel removes the Use current FIR filter option and selects the Use
default Nyquist FIR filter option instead as the default setting.
3-72
In the center section FDATool provides choices that let you pick the filter
design method to use.
The rightmost section offers options that control filter configuration when you
select Cascaded-Integrator Comb (CIC) as the design method in the center
section. Both the Decimator type and Interpolator type filters let you use
the Cascaded-Integrator Comb (CIC) option to design multirate filters.
Here are all the options available when you switch to multirate filter design
mode. Each option listed includes a brief description of what the option does
when you use it.
Select and Configure Your Filter
Option
Description
Type
3-73
Description
decimation factor is 3, FDATool reduces 6/3 to
2/1 when you design the rate changer. But if the
interpolation factor is 8 and the decimation factor
is 3, FDATool designs the filter without change.
Interpolation
Factor
Decimation Factor
Sampling
Frequency
Units
Fs
3-74
Option
Description
Use a default
Nyquist Filter
Cascaded
Integrator-Comb
(CIC)
Description
Hold Interpolator
(Zero-order)
Linear Interpolator
(First-order)
To see the difference between hold interpolation and linear interpolation, the
following figure presents a sine wave signal s1 in three forms:
The top subplot in the figure presents signal s1 without interpolation.
The middle subplot shows signal s1 interpolated by a linear interpolator
with an interpolation factor of 5.
The bottom subplot shows signal s1 interpolated by a hold interpolator with
an interpolation factor of 5.
You see in the bottom figure the sample and hold nature of hold interpolation,
and the first-order linear interpolation applied by the linear interpolator.
3-75
Uninterpolated Signal s1
1
0.5
0
0.5
1
10
40
45
50
40
45
50
10
15
20
25
30
35
10
15
20
25
Samples
30
35
3-76
Description
Differential Delay
Sets the differential delay for the CIC filter. Usually a value
of one or two is appropriate.
Number of Sections
in
the side bar. FDATool switches to multirate filter design mode, showing
the multirate design panel.
from the Type list. The Interpolation Factor and Decimation Factor
options become available.
5 In Interpolation Factor, use the up arrow to set the interpolation factor
to 7.
6 Using the up arrow in Decimation Factor, set 3 as the decimation factor.
7 Select Use a default Nyquist FIR filter. You could design the rate
After designing the filter, FDATool returns with the specifications for
your new filter displayed in Current Filter Information, and shows
the magnitude response of the filter.
3-77
You can test the filter by exporting it to your workspace and using it to filter a
signal. For information about exporting filters, refer to Import and Export
Quantized Filters on page 3-54.
Design a CIC Decimator for 8 Bit Input/Output Data. Another kind of
filter you can design in FDATool is Cascaded-Integrator Comb (CIC) filters.
FDATool provides the options needed to configure your CIC to meet your
needs.
1 Launch FDATool and design the default FIR lowpass filter. Designing a
3-78
FDATool designs the filter, shows the magnitude response in the analysis
area, and updates the current filter information to show that you designed
a tenth-order cascaded-integrator comb decimator with two sections. Notice
the source is Multirate Design, indicating you used the multirate design
mode in FDATool to make the filter. FDATool should look like this now.
3-79
3-80
in FDATool.
2 Click the Set Quantization Parameters button on the side bar.
3 From the Filter Arithmetic list on the Filter Arithmetic pane, select
When you current filter is a CIC filter, the options on the Input/Output and
Filter Internals panes change to provide specific features for CIC filters.
3-81
Input/Output. The options that specify how your CIC filter uses input and
output values are listed in the table below.
Option Name
Description
Input fraction
length
Avoid overflow
The available options change when you change the Filter precision setting.
Moving from Full to Specify all adds increasing control by enabling more
input and output word options.
Filter Internals. With a CIC filter as your current filter, the Filter
precision option on the Filter Internals pane includes modes for controlling
the filter word and fraction lengths.
3-82
There are four usage modes for this (the same mode you select for the
FilterInternals property in CIC filters at the MATLAB prompt).
Full All word and fraction lengths set to Bmax + 1, called Baccum by Harris
in [2]. Full Precision is the default setting.
Minimum section word lengths Set the section word lengths to
minimum values that meet roundoff noise and output requirements as
defined by Hogenauer in [3].
Specify word lengths Enables the Section word length option for
you to enter word lengths for each section. Enter either a scalar to use the
same value for every section, or a vector of values, one for each section.
Specify all Enables the Section fraction length option in addition
to Section word length. Now you can provide both the word and fraction
lengths for each section, again using either a scalar or a vector of values.
3-83
5 Click the Export button. The multirate filter object, Hm in this example,
Introduction
After you design or import a filter in FDATool, the realize model feature
lets you create a Simulink subsystem block that implements your filter. The
generated filter subsystem block uses either the Digital Filter block or the
delay, gain, and sum blocks in Simulink. If you do not have a Fixed-Point
Designer license, FDATool still realizes your model using blocks in
fixed-point mode from Simulink, but you cannot run any model that includes
your filter subsystem block in Simulink.
on the sidebar.
The following panel shows the options for configuring how FDATool
implements your filter as a Simulink block.
3-84
mode.
2 From the Destination list under Model, select either:
your filter as a subsystem block that consists of Sum, Gain, and Delay
blocks.
3-85
Optimize for zero gains removes zero gain blocks from the model
realization
Optimize for unity gains replaces unity gain blocks with direct
connections to adjacent blocks
Optimize for negative gains replaces negative gain blocks by a
change of sign at the nearest sum block
Optimize delay chains replaces cascaded delay blocks with a single
delay block that produces the equivalent gain
Optimize for unity scale values removes all scale value
multiplications by 1 from the filter structure
7 Click Realize Model to realize your quantized filter as a subsystem block
3-86
Structure
Description
firdecim
firtdecim
linearinterp
Linear interpolators
firinterp
multirate polyphase
Multirate filters
holdinterp
Structure
Description
dfilt.allpass
dfilt.cascadeallpass
dfilt.cascadewdfallpass
mfilt.iirdecim
mfilt.iirwdfdecim
mfilt.iirinterp
mfilt.iirwdfinterp
dfilt.wdfallpass
3-87
Overview of Transformations
Converting existing FIR or IIR filter designs to a modified IIR form is often
done using allpass frequency transformations. Although the resulting designs
can be considerably more expensive in terms of dimensionality than the
prototype (original) filter, their ease of use in fixed or variable applications is
a big advantage.
The general idea of the frequency transformation is to take an existing
prototype filter and produce another filter from it that retains some of the
characteristics of the prototype, in the frequency domain. Transformation
functions achieve this by replacing each delaying element of the prototype
filter with an allpass filter carefully designed to have a prescribed phase
characteristic for achieving the modifications requested by the designer.
The basic form of mapping commonly used is
HT ( z) = Ho[ H A ( z)]
The HA(z) is an Nth-order allpass mapping filter given by
3-88
H A ( z) = S
0 = 1
i z i
i=0
N
i z N + i
N A ( z)
DA ( z)
i=0
where
Ho(z) Transfer function of the prototype filter
HA(z) Transfer function of the allpass mapping filter
HT(z) Transfer function of the target filter
Lets look at a simple example of the transformation given by
HT ( z) = Ho ( z)
The target filter has its poles and zeroes flipped across the origin of the real
and imaginary axes. For the real filter prototype, it gives a mirror effect
against 0.5, which means that lowpass Ho(z) gives rise to a real highpass
HT(z). This is shown in the following figure for the prototype filter designed as
a third-order halfband elliptic filter.
3-89
Target filter
0
10
10
20
20
|H()| in dB
|H()| in dB
Prototype filter
0
30
40
50
60
30
40
50
0.2
0.4
0.6
0.8
1
Normalized Frequency ( rad/sample)
60
0.2
0.4
0.6
0.8
1
Normalized Frequency ( rad/sample)
H (wnew ) = old
The graphical interpretation of the frequency transformation is shown in the
figure below. The complex multiband transformation takes a real lowpass
filter and converts it into a number of passbands around the unit circle.
3-90
H A ( z) =
1 + 1 z1 + 2 z2
2 + 1 z1 + z2
The two degrees of freedom provided by 1 and 2 choices are not fully used
by the usual restrictive set of flat-top classical mappings like lowpass to
bandpass. Instead, any two transfer function features can be migrated to
(almost) any two other frequency locations if 1 and 2 are chosen so as to keep
the poles of HA(z) strictly outside the unit circle (since HA(z) is substituted
for z in the prototype transfer function). Moreover, as first pointed out
by Constantinides, the selection of the outside sign influences whether the
original feature at zero can be moved (the minus sign, a condition known
3-91
3-92
10
20
30
40
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
The results of all three approaches are completely different. For each of them
only the selected features were positioned precisely where they were required.
In the first case the DC is moved toward the left passband edge just like all
the other features close to the left edge being squeezed there. In the second
case the right passband edge was pushed way out of the expected target as
the precise position of DC was required. In the third case the left passband
edge was pulled toward the DC in order to position it at the correct frequency.
3-93
The conclusion is that if only the DC can be anywhere in the passband, the
edges of the passband should have been selected for the transformation. For
most of the cases requiring the positioning of passbands and stopbands,
designers should always choose the position of the edges of the prototype
filter in order to make sure that they get the edges of the target filter in the
correct places. Frequency responses for the three cases considered are shown
in the figure. The prototype filter was a third-order elliptic lowpass filter
with cutoff frequency at 0.5.
The MATLAB code used to generate the figure is given here.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
In the example the requirements are set to create a real bandpass filter
with passband edges at 0.1 and 0.3 out of the real lowpass filter having the
cutoff frequency at 0.5. This is attempted in three different ways. In the first
approach both edges of the passband are selected, in the second approach the
left edge of the passband and the DC are chosen, while in the third approach
the DC and the right edge of the passband are taken:
[num1,den1] = iirlp2xn(b, a, [-0.5, 0.5], [0.1, 0.3]);
[num2,den2] = iirlp2xn(b, a, [-0.5, 0.0], [0.1, 0.2]);
[num3,den3] = iirlp2xn(b, a, [ 0.0, 0.5], [0.2, 0.3]);
3-94
Ho ( z) =
( z zi )
i =1
N
( z pi )
i =1
the mapping will replace each pole, pi, and each zero, zi, with a number of
poles and zeros equal to the order of the allpass mapping filter:
N
Ho ( z) =
i =1
N
i =1
N 1
N 1
S k zk zi k z N k
k= 0
k= 0
N 1
N 1
S k zk pi k z N k
k= 0
k= 0
The root finding needs to be used on the bracketed expressions in order to find
the poles and zeros of the target filter.
When the prototype filter is described in the numerator-denominator form:
HT ( z) =
0 z N + 1 z N 1 + + N
0 z N + 1 z N 1 + + N
z = H A ( z)
HT ( z) =
1 N A ( z) N + 2 N A ( z) N 1 DA ( z) + + N DA ( z) N
1 N A ( z) N + 2 N A ( z) N 1 DA ( z) + + N DA ( z) N
For each coefficient i and i of the prototype filter the NAth-order polynomials
must be convolved N times. Such approach may cause rounding errors for
large prototype filters and/or high order mapping filters. In such a case the
user should consider the alternative of doing the mapping using via poles
and zeros.
3-95
Overview
This section discusses real frequency transformations that take the real
lowpass prototype filter and convert it into a different real target filter. The
target filter has its frequency response modified in respect to the frequency
3-96
H A ( z) = z1
1 z 1
z 1
with given by
cos old
2
=
sin ( 2
new )
2 old
otherwise
sin
2 old
where
old Frequency location of the selected feature in the prototype filter
new Position of the feature originally at old in the target filter
The following example shows how this transformation can be used to move
the response of the prototype lowpass filter in either direction. Please note
that because the target filter must also be real, the response of the target
filter will inherently be disturbed at frequencies close to Nyquist and close to
DC. Here is the MATLAB code for generating the example in the figure.
3-97
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.9
Target filter
0
|H()| in dB
10
20
30
40
t
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
3-98
1 z 1
H A ( z) =
z 1
with given by
( new )
2 old
=
where
old Frequency location of the selected feature in the prototype filter
new Frequency location of the same feature in the target filter
The example below shows how to modify the cutoff frequency of the prototype
filter. The MATLAB code for this example is shown in the following figure.
The prototype filter is a halfband elliptic, real, third-order filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-99
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.8
0.9
Target filter
0
|H()| in dB
10
20
30
40
t
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
1 + z 1
H A ( z) =
+ z 1
with given by
3-100
where
old Frequency location of the selected feature in the prototype filter
new Frequency location of the same feature in the target filter
The example below shows how to convert the lowpass filter into a highpass
filter with arbitrarily chosen cutoff frequency. In the MATLAB code below,
the lowpass filter is converted into a highpass with cutoff frequency shifted
from 0.5 to 0.75. Results are shown in the figure.
The prototype filter is a halfband elliptic, real, third-order filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-101
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.8
0.9
Target filter
0
|H()| in dB
10
20
30
40
t
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
1 (1 + ) z1 z2
H A ( z) =
(1 + ) z1 + z2
3-102
The example transformation creates the passband between 0.5 and 0.75:
[num,den] = iirlp2bp(b, a, 0.5, [0.5, 0.75]);
3-103
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.8
0.9
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
0.1
0.2
t2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
H A ( z) =
1 (1 + ) z1 + z2
(1 + ) z1 + z2
3-104
3-105
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.9
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
t2
0.8
H A ( z) = S
0 = 1
3-106
i z i
i=0
N
i z N + i
i=0
0 = 1 k = 1,, N
2
k = S
2
where
old,k Frequency location of the first feature in the prototype filter
new,k Position of the feature originally at old,k in the target filter
The mobility factor, S, specifies the mobility or either DC or Nyquist feature:
1 Nyquist
S=
DC
1
The example below shows how this transformation can be used to convert the
prototype lowpass filter with cutoff frequency at 0.5 into a filter having a
number of bands positioned at arbitrary edge frequencies 1/5, 2/5, 3/5 and 4/5.
Parameter S was such that there is a passband at DC. Here is the MATLAB
code for generating the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-107
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.9
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
0.1
0.2
t2
t3
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
t4
0.8
H A ( z) = S
0 = 1
i z i
i=0
N
i z N + i
i=0
3-108
N
i
N i
N i zold, k znew, k S znew, k = zold, k S znew, k
i =1
j
zold, k = e old,k
j
znew, k = e new,k
k = 1,, N
where
old,k Frequency location of the first feature in the prototype filter
new,k Position of the feature originally at old,k in the target filter
The mobility factor, S, specifies the mobility of either DC or Nyquist feature:
1 Nyquist
S=
DC
1
The example below shows how this transformation can be used to move
features of the prototype lowpass filter originally at -0.5 and 0.5 to their new
locations at 0.5 and 0.75, effectively changing a position of the filter passband.
Here is the MATLAB code for generating the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-109
Prototype filter
0
|H()|in dB
10
20
30
40
o2
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.9
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
t2
0.8
Overview
This section discusses complex frequency transformation that take the
complex prototype filter and convert it into a different complex target
3-110
filter. The target filter has its frequency response modified in respect to the
frequency response of the prototype filter according to the characteristic of the
applied frequency transformation from:
H A ( z) = z1
with given by
= e j 2 ( new old )
where
old Frequency location of the selected feature in the prototype filter
new Position of the feature originally at old in the target filter
A special case of the complex frequency shift is a, so called, Hilbert
Transformer. It can be designed by setting the parameter to ||=1, that is
1 forward
=
1 inverse
The example below shows how to apply this transformation to rotate the
response of the prototype lowpass filter in either direction. Please note that
because the transformation can be achieved by a simple phase shift operator,
all features of the prototype filter will be moved by the same amount. Here is
the MATLAB code for generating the example in the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
3-111
|H()|in dB
10
20
30
40
o
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
0.8
0.6
0.8
Target filter
0
|H()| in dB
10
20
30
40
t
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
H A ( z) =
z 1
z1
3-112
= e j (new old )
where
old Frequency location of the selected feature in the prototype filter
new,1 Position of the feature originally at (-old) in the target filter
new,2 Position of the feature originally at (+old) in the target filter
The following example shows the use of such a transformation for converting
a real halfband lowpass filter into a complex bandpass filter with band edges
at 0.5 and 0.75. Here is the MATLAB code for generating the example in
the figure.
The prototype filter is a half band elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-113
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
0.8
0.8
Target filter
0
|H()| in dB
10
20
30
40
t1
50
t2
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
H A ( z) =
z 1
z1
= e j (new old )
3-114
where
old Frequency location of the selected feature in the prototype filter
new,1 Position of the feature originally at (-old) in the target filter
new,2 Position of the feature originally at (+old) in the target filter
The example below shows the use of such a transformation for converting a
real halfband lowpass filter into a complex bandstop filter with band edges
at 0.5 and 0.75. Here is the MATLAB code for generating the example in
the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-115
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
0.8
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
t2
0.6
0.8
3-116
H A ( z) = S
0 = 1
i z i
i=0
N
i z N + i
i=0
N
(i ) cos 1, k cos 2, k + (i ) sin 1, k + sin 2, k = cos 3, k
i =1
N
( ) sin sin ( ) cos + cos = sin
3, k
i
1, k
2, k
i
1, k
2, k
i =1
=
(1) k + new, k ( N k)
1, k
old
k
=
+
new, k
2, k
k
3, k = old (1) + new, k N
k = 1 N
where
old Frequency location of the selected feature in the prototype filter
new,i Position of features originally at old in the target filter
Parameter S is the additional rotation factor by the frequency distance C,
giving the additional flexibility of achieving the required mapping:
S = e jC
The example shows the use of such a transformation for converting a prototype
real lowpass filter with the cutoff frequency at 0.5 into a multiband complex
filter with band edges at 0.2, 0.4, 0.6 and 0.8, creating two passbands around
the unit circle. Here is the MATLAB code for generating the figure.
3-117
Prototype filter
0
|H()|in dB
10
20
30
40
o
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
0.8
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
1
0.8
0.6
t2
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
t3
0.6
t4
0.8
3-118
H A ( z) = S
0 = 1
i z i
i=0
N
i z N + i
i=0
N
(i ) cos 1, k cos 2, k + (i ) sin 1, k + sin 2, k = cos 3, k
i =1
N
( ) sin sin ( ) cos + cos = sin
3, k
i
i
1, k
2, k
1, k
2, k
i =1
1, k = old, k + new, k ( N k)
2
2, k = 2 2C + new, k k
= old, k + new, k N
3, k
2
=
1
k
N
where
old,k Frequency location of the first feature in the prototype filter
new,k Position of the feature originally at old,k in the target filter
Parameter S is the additional rotation factor by the frequency distance C,
giving the additional flexibility of achieving the required mapping:
S = e jC
The following example shows how this transformation can be used to move
one selected feature of the prototype lowpass filter originally at -0.5 to two
new frequencies -0.5 and 0.1, and the second feature of the prototype filter
3-119
from 0.5 to new locations at -0.25 and 0.3. This creates two nonsymmetric
passbands around the unit circle, creating a complex filter. Here is the
MATLAB code for generating the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
|H()|in dB
10
20
30
40
50
60
1
0.8
0.6
o1
o2
o3
o4
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
0.6
0.8
0.6
0.8
Target filter
0
|H()| in dB
10
20
30
40
50
60
1
t1
0.8
0.6
t2
t3
t4
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
3-120
H A ( z) =
( z1 )
z1
=e
=e
j (old ,2 old ,1 )
j (new,2 neew,1 )
where
old,1 Frequency location of the first feature in the prototype filter
old,2 Frequency location of the second feature in the prototype filter
new,1 Position of the feature originally at old,1 in the target filter
new,2 Position of the feature originally at old,2 in the target filter
The following example shows how this transformation can be used to modify
the position of the passband of the prototype filter, either real or complex. In
the example below the prototype filter passband spanned from 0.5 to 0.75.
It was converted to having a passband between -0.5 and 0.1. Here is the
MATLAB code for generating the figure.
The prototype filter is a halfband elliptic, real, third-order lowpass filter:
[b, a] = ellip(3, 0.1, 30, 0.409);
3-121
Prototype filter
0
|H()|in dB
10
20
30
40
o1
50
60
1
0.8
0.6
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
o2
0.6
0.8
0.6
0.8
Target filter
0
|H()| in dB
10
20
30
40
t1
50
60
1
0.8
0.6
t2
0.4
0.2
0
0.2
0.4
Normalized Frequency ( rad/sample)
3-122
Filter Implementation
Once you have designed your filter using FDATool, the block automatically
realizes the filter using the filter structure you specify. You can then use
the block to filter signals in your model. You can also fine-tune the filter by
changing the filter specification parameters during a simulation. The outputs
of the Digital Filter Design block numerically match the outputs of the DSP
System Toolbox filter function and the MATLAB filter function.
3-123
Similarities
The Digital Filter Design block and Filter Realization Wizard are similar
in the following ways:
Filter design and analysis options Both blocks use the Filter Design and
Analysis Tool (FDATool) GUI for filter design and analysis.
Output values If the output of both blocks is double-precision floating
point, single-precision floating point, or fixed point, the output values of
both blocks numerically match the output of the filter method of the
dfilt object.
3-124
Differences
The Digital Filter Design block and Filter Realization Wizard handle the
following things differently:
Supported filter structures Both blocks support many of the same
basic filter structures, but the Filter Realization Wizard supports more
structures than the Digital Filter Design block. This is because the block
can implement filters using Sum, Gain, and Delay blocks. See the Filter
Realization Wizard and Digital Filter Design block reference pages for a
list of all the structures they support.
Data type support The Filter Realization Wizard block supports singleand double-precision floating-point computation for all filter structures and
fixed-point computation for some filter structures. The Digital Filter Design
block only supports single- and double-precision floating-point computation.
Block versus Wizard The Digital Filter Design block is the filter itself,
but the Filter Realization Wizard block just enables you to create new
filters and put them in an existing model. Thus, the Filter Realization
Wizard is not a block that processes data in your model, it is a wizard that
generates filter blocks (or subsystems) which you can then use to process
data in your model.
3-125
Use to visualize the filter structure, as the block can build the filter
from Sum, Gain, and Delay blocks.
See Filter Realization Wizard on page 3-134 and the Filter Realization
Wizard block reference page for information.
Your Digital Filter Design block now represents a filter with the
parameters you specified.
6 From the Edit menu, select Convert Structure.
3-126
The Digital Filter Design block now represents a lowpass filter with a
Direct-Form FIR Transposed structure. The filter passes all frequencies up
to 20% of the Nyquist frequency (half the sampling frequency), and stops
frequencies greater than or equal to 50% of the Nyquist frequency as defined
by the wpass and wstop parameters. In the next topic, Create a Highpass
Filter in Simulink on page 3-127, you use a Digital Filter Design block
to create a highpass filter. For more information about implementing a
pre-designed filter, see Digital Filter Block on page 3-147.
3-126 is not open on your desktop, you can open an equivalent model by
typing
ex_filter_ex4
3-127
wpass = 0.5
5 Click the Design Filter button at the bottom of the GUI to design the filter.
Your Digital Filter Design block now represents a filter with the
parameters you specified.
6 In the Edit menu, select Convert Structure.
The block now implements a highpass filter with a direct form FIR transpose
structure. The filter passes all frequencies greater than or equal to 50% of
the Nyquist frequency (half the sampling frequency), and stops frequencies
less than or equal to 20% of the Nyquist frequency as defined by the wpass
and wstop parameters. This highpass filter is the opposite of the lowpass
filter described in Create a Lowpass Filter in Simulink on page 3-126. The
highpass filter passes the frequencies stopped by the lowpass filter, and
stops the frequencies passed by the lowpass filter. In the next topic, Filter
High-Frequency Noise in Simulink on page 3-128, you use these Digital
Filter Design blocks to create a model capable of removing high frequency
noise from a signal. For more information about implementing a pre-designed
filter, see Digital Filter Block on page 3-147.
3-127 is not open on your desktop, you can open an equivalent model by
typing
3-128
ex_filter_ex5
Block
Library
Quantity
Add
Random Source
Sources
Sine Wave
Sources
Time Scope
Sinks
3 Set the parameters for these blocks as indicated in the following table.
Leave the parameters not listed in the table at their default settings.
Parameter Settings for the Other Blocks
Block
Parameter Setting
Add
Random
Source
3-129
Parameter Setting
Sine Wave
Frequency (Hz) = 75
Sample time = 1/1000
Samples per frame = 50
Time Scope
4 Connect the blocks as shown in the following figure. You might need to
3-130
Start time = 0
Stop time = 5
Type = Fixed-step
Solver = Discrete (no continuous states)
7 In the model window, from the Simulation menu, choose Run.
The model simulation begins and the scope displays the three input signals.
8 After simulation is complete, select View > Legend from the Time
Scope menu. The legend appears in the Time Scope window. You can
click-and-drag it anywhere on the scope display. To change the channel
names, double-click inside the legend and replace the default channel
names with the following:
Add = Noisy Sine Wave
Digital Filter Design Lowpass = Filtered Noisy Sine Wave
Sine Wave = Original Sine Wave
In the next step, you will set the color, style, and marker of each channel.
9 In the Time Scope window, select View > Line Properties, and set the
following:
Line
Style
Marker
Color
None
Black
Filtered Noisy
Sine Wave
diamond
Red
Original Sine
Wave
None
Blue
3-131
You can see that the lowpass filter filters out the high-frequency noise in
the noisy sine wave.
3-132
You have now used Digital Filter Design blocks to build a model that removes
high frequency noise from a signal. For more information about these blocks,
see the Digital Filter Design block reference page. For information on another
block capable of designing and implementing filters, see Filter Realization
Wizard on page 3-134. To learn how to save your filter designs, see Saving
and Opening Filter Design Sessions on page 13-38 in the Signal Processing
Toolbox documentation. To learn how to import and export your filter designs,
see Import and Export Quantized Filters on page 3-54 in the DSP System
Toolbox documentation.
3-133
3-134
load mtlb
soundsc(mtlb,Fs)
at the MATLAB command line. You should hear a voice say MATLAB.
This is the signal to which you will add noise.
2 Create a noise signal by typing
noise = cos(2*pi*3*Fs/8*(0:length(mtlb)-1)/Fs)';
at the command line. You can hear the noise signal by typing
soundsc(noise,Fs)
3 Add the noise to the original signal by typing
u = mtlb + noise;
u = u/max(abs(u));
at the command line. You scale the signal to try to avoid overflows later on.
You can hear the scaled signal with noise by typing
soundsc(u,Fs)
5 View the scaled signal with noise by typing
spectrogram(u,256,[],[],Fs);colorbar
3-135
In the spectrogram, you can see the noise signal as a line at about 2800 Hz,
which is equal to 3*Fs/8.
block from the Filtering / Filter Implementations library into the model.
3-136
Realize Model panel of the Filter Design and Analysis Tool (FDATool)
appears.
8 Click the Design Filter button (
3-137
3-138
Make sure the Best precision fraction lengths check box is selected
on the Coefficients pane.
The Set quantization parameters panel should appear as follows.
3-139
). This
Note You do not have to keep the Filter Realization Wizard block in the
same model as the generated Filter block. However, for this tutorial, we
will keep the blocks in the same model.
3-140
14 Double-click the Filter subsystem block in your model to view the filter
implementation.
port of your filter block. Your blocks should now be connected as follows.
17 Open the Signal From Workspace block dialog box and set the Signal
parameter to u. Click OK to save your changes and close the dialog box.
18 Open the Model Configuration Parameters dialog box from the
Simulation menu of the model. In the Solver pane of the dialog, set the
following fields:
Stop time = length(u)-1
Type = Fixed-step
Click OK to save your changes and close the dialog box.
19 Run the model.
20 From the Display menu of the model, select Signals & Ports > Port Data
Types. You can now see that the input to the Filter block is a signal of type
double and the output of the Filter block has a data type of sfix16_En11.
3-141
soundsc(yout,Fs)
at the command line to hear the output of the filter. You should hear a voice
say MATLAB. The noise portion of the signal should be close to inaudible.
22 Type
3-142
figure
spectrogram(yout,256,[],[],Fs);colorbar
From the colorbars at the side of the input and output spectrograms, you can
see that the noise has been reduced by about 40 dB.
3-143
button
3-144
3-145
3-146
3-147
The Digital Filter block in your model now represents a lowpass filter. In the
next topic, Implement a Highpass Filter in Simulink on page 3-149, you use
a Digital Filter block to implement a highpass filter. For more information
3-148
about the Digital Filter block, see the Digital Filter block reference page. For
more information about designing and implementing a new filter, see Digital
Filter Design Block on page 3-123.
on page 3-148 is not open on your desktop, you can open an equivalent
model by typing
ex_filter_ex1
3-149
You have now successfully implemented a highpass filter. In the next topic,
Filter High-Frequency Noise in Simulink on page 3-150, you use these
Digital Filter blocks to create a model capable of removing high frequency
noise from a signal. For more information about designing and implementing
a new filter, see Digital Filter Design Block on page 3-123.
on page 3-149 is not open on your desktop, you can open an equivalent
model by typing
ex_filter_ex2
3-150
Block
Library
Quantity
Add
Random Source
Sources
Sine Wave
Sources
Time Scope
Sinks
4 Set the parameters for the rest of the blocks as indicated in the following
table. For any parameters not listed in the table, leave them at their
default settings.
Block
Parameter Setting
Add
Random Source
Sine Wave
Frequency (Hz) = 75
Sample time = 1/1000
Samples per frame = 50
Time Scope
3-151
5 Connect the blocks as shown in the following figure. You may need to resize
Start time = 0
Stop time = 5
Type = Fixed-step
Solver = discrete (no continuous states)
8 In the model window, from the Simulation menu, choose Run.
The model simulation begins and the Scope displays the three input signals.
3-152
9 After simulation is complete, select View > Legend from the Time
Scope menu. The legend appears in the Time Scope window. You can
click-and-drag it anywhere on the scope display. To change the channel
names, double-click inside the legend and replace the current numbered
channel names with the following:
Add = Noisy Sine Wave
Digital Filter Lowpass = Filtered Noisy Sine Wave
Sine Wave = Original Sine Wave
In the next step, you will set the color, style, and marker of each channel.
10 In the Time Scope window, select View > Line Properties, and set the
following:
Line
Style
Marker
Color
None
Black
Filtered Noisy
Sine Wave
diamond
Red
Original Sine
Wave
None
Blue
You can see that the lowpass filter filters out the high-frequency noise in
the noisy sine wave.
3-153
3-154
You have now used Digital Filter blocks to build a model that removes high
frequency noise from a signal. For more information about designing and
implementing a new filter, see Digital Filter Design Block on page 3-123.
3-155
Time-varying filters are filters whose coefficients change with time. You
can specify a time-varying filter that changes once per frame or once per
sample and you can filter multiple channels with each filter. However, you
cannot apply different filters to each channel; all channels must be filtered
with the same filter.
To specify a time-varying filter:
1 Set the Coefficient source parameter to Input port(s), which enables
or One filter per sample depending on how often you want to update
the filter coefficients.
3 Provide vectors of numerator, denominator, or reflection coefficients to the
block input ports for filter coefficients. The series of vectors must arrive at
their ports at a specific rate, and must be of certain lengths.
4 Select or clear the First denominator coefficient = 1, remove a0 term
3-156
3-157
If you enter a scalar, the value is used as the gain value before the first
section of the second-order filter. The rest of the gain values are set to 1.
If you enter a vector of M+1 values, each value is used for a separate
section of the filter. For example, the first element is the first gain value,
the second element is the second gain value, and so on.
You can use the ss2sos and tf2sos functions from Signal Processing Toolbox
software to convert a state-space or transfer function description of your filter
into the second-order section description used by this block.
b01
b
02
b0 M
b11
b12
b21
b22
a01
a02
a11
a12
b1 M
b2 M
a0 M
a1 M
a21
a22
a2 M
The block normalizes each row by a1i to ensure a value of 1 for the zero-delay
denominator coefficients.
Note You can also use the Biquad Filter block to implement a static
biquadratic IIR filter.
3-158
Butterworth
Chebyshev I
Chebyshev II
Elliptic
Lowpass
p , R p
s, R s
p, R p, R s
Highpass
p , R p
s, R s
p, R p, R s
Bandpass
p1, p2
p1, p2, Rp
s1, s2, Rs
Bandstop
p1, p2
p1, p2, Rp
s1, s2, Rs
3-159
3-160
4
Adaptive Filters
Learn how to design and implement adaptive filters.
Overview of Adaptive Filters and Applications on page 4-2
Adaptive Filters in DSP System Toolbox Software on page 4-10
LMS Adaptive Filters on page 4-14
RLS Adaptive Filters on page 4-35
Signal Enhancement Using LMS and Normalized LMS on page 4-41
Adaptive Filters in Simulink on page 4-51
Selected Bibliography on page 4-66
Adaptive Filters
4-2
Desired Signal
d(k)
Input Signal
x(k)
Output Signal
y(k)
+
_
SUM
Error Signal
e(k)
Block Diagram That Defines the Inputs and Output of a Generic RLS Adaptive
Filter
The next figure provides the general adaptive filter setup with inputs and
outputs.
Desired Signal
d(k)
Input Signal
x(k)
Output Signal
y(k)
+
_
SUM
Error Signal
e(k)
Adapting Algorithm
4-3
Adaptive Filters
4-4
approach is beyond the scope of this Users Guide. However, a few guidelines
can help you make your choice.
Two main considerations frame the decision how you plan to use the filter
and the filter algorithm to use.
When you begin to develop an adaptive filter for your needs, most likely the
primary concern is whether using an adaptive filter is a cost-competitive
approach to solving your filtering needs. Generally many areas determine the
suitability of adaptive filters (these areas are common to most filtering and
signal processing applications). Four such areas are
Filter consistency Does your filter performance degrade when the filter
coefficients change slightly as a result of quantization, or you switch
to fixed-point arithmetic? Will excessive noise in the signal hurt the
performance of your filter?
Filter performance Does your adaptive filter provide sufficient
identification accuracy or fidelity, or does the filter provide sufficient signal
discrimination or noise cancellation to meet your requirements?
Tools Do tools exist that make your filter development process easier?
Better tools can make it practical to use more complex adaptive algorithms.
DSP requirements Can your filter perform its job within the constraints
of your application? Does your processor have sufficient memory,
throughput, and time to use your proposed adaptive filtering approach?
Can you trade memory for throughput: use more memory to reduce the
throughput requirements or use a faster signal processor?
Of the preceding considerations, characterizing filter consistency or
robustness may be the most difficult.
The simulations in DSP System Toolbox software offers a good first step in
developing and studying these issues. LMS algorithm filters provide both a
relatively straightforward filters to implement and sufficiently powerful tool
for evaluating whether adaptive filtering can be useful for your problem.
Additionally, starting with an LMS approach can form a solid baseline against
which you can study and compare the more complex adaptive filters available
in the toolbox. Finally, your development process should, at some time, test
4-5
Adaptive Filters
your algorithm and adaptive filter with real data. For truly testing the value
of your work there is no substitute for actual data.
System Identification
One common adaptive filter application is to use adaptive filters to identify
an unknown system, such as the response of an unknown communications
channel or the frequency response of an auditorium, to pick fairly divergent
applications. Other applications include echo cancellation and channel
identification.
In the figure, the unknown system is placed in parallel with the adaptive
filter. This layout represents just one of many possible structures. The shaded
area contains the adaptive filter system.
Unknown System
d(k)
x(k)
Adaptive Filter
text
y(k)
+
_ SUM
e(k)
Clearly, when e(k) is very small, the adaptive filter response is close to the
response of the unknown system. In this case the same input feeds both the
adaptive filter and the unknown. If, for example, the unknown system is a
modem, the input often represents white noise, and is a part of the sound you
hear from your modem when you log in to your Internet service provider.
4-6
the desired signal d(k) path to keep the data at the summation synchronized.
Adding the delay keeps the system causal.
Including the delay to account for the delay caused by the unknown system
prevents this condition.
Plain old telephone systems (POTS) commonly use inverse system
identification to compensate for the copper transmission medium. When
you send data or voice over telephone lines, the copper wires behave like a
filter, having a response that rolls off at higher frequencies (or data rates)
and having other anomalies as well.
Adding an adaptive filter that has a response that is the inverse of the wire
response, and configuring the filter to adapt in real time, lets the filter
compensate for the rolloff and anomalies, increasing the available frequency
output range and data rate for the telephone system.
4-7
Adaptive Filters
s(k) + n(k)
n'(k)
x(k)
Adaptive Filter
y(k)
d(k)
+
_
SUM
e(k)
So long as the input noise to the filter remains correlated to the unwanted
noise accompanying the desired signal, the adaptive filter adjusts its
coefficients to reduce the value of the difference between y(k) and d(k),
removing the noise and resulting in a clean signal in e(k). Notice that in
this application, the error signal actually converges to the input data signal,
rather than converging to zero.
Prediction
Predicting signals requires that you make some key assumptions. Assume
that the signal is either steady or slowly varying over time, and periodic over
time as well.
s(k)
Delay
x(k)
Adaptive Filter
y(k)
d(k)
+
_
SUM
e(k)
Accepting these assumptions, the adaptive filter must predict the future
values of the desired signal based on past values. When s(k) is periodic and
the filter is long enough to remember previous values, this structure with the
delay in the input signal, can perform the prediction. You might use this
structure to remove a periodic signal from stochastic noise signals.
Finally, notice that most systems of interest contain elements of more than
one of the four adaptive filter structures. Carefully reviewing the real
structure may be required to determine what the adaptive filter is adapting to.
4-8
Also, for clarity in the figures, the analog-to-digital (A/D) and digital-to-analog
(D/A) components do not appear. Since the adaptive filters are assumed to be
digital in nature, and many of the problems produce analog data, converting
the input signals to and from the analog domain is probably necessary.
4-9
Adaptive Filters
Algorithms
For adaptive filter (adaptfilt) objects, the algorithm string determines
which adaptive filter algorithm your adaptfilt object implements. Each
available algorithm entry appears in one of the tables along with a brief
description of the algorithm. Click on the algorithm in the first column to get
more information about the associated adaptive filter technique.
LMS based adaptive filters
RLS based adaptive filters
Affine projection adaptive filters
Adaptive filters in the frequency domain
Lattice based adaptive filters
4-10
adaptfilt.adjlms
adaptfilt.blms
adaptfilt.blmsfft
adaptfilt.dlms
adaptfilt.filtxlms
adaptfilt.lms
adaptfilt.nlms
adaptfilt.sd
adaptfilt.se
adaptfilt.ss
adaptfilt.ftf
adaptfilt.qrdrls
adaptfilt.hrls
adaptfilt.hswrls
adaptfilt.rls
adaptfilt.swrls
adaptfilt.swftf
4-11
Adaptive Filters
adaptfilt.ap
adaptfilt.apru
adaptfilt.bap
Adaptive Filter
Method
adaptfilt.fdaf
adaptfilt.pbfdaf
adaptfilt.pbufdaf
adaptfilt.tdafdct
adaptfilt.tdafdft
adaptfilt.ufdaf
4-12
adaptfilt.gal
adaptfilt.lsl
4-13
Adaptive Filters
4-14
adaptive filter. The correction applied to the current filter weights for each
successive iteration depends on both the sign of x(k) and the sign of e(k).
To demonstrate the differences and similarities among the various LMS
algorithms supplied in the toolbox, the LMS and NLMS adaptive filter
examples use the same filter for the unknown system. The unknown filter is
the constrained lowpass filter from firgr and fircband examples.
[b,err,res]=firgr(12,[0 0.4 0.5 1], [1 1 0 0], [1 0.2],...
{'w' 'c'});
From the figure you see that the filter is indeed lowpass and constrained to
0.2 ripple in the stopband. With this as the baseline, the adaptive LMS filter
examples use the adaptive LMS algorithms and their initialization functions
to identify this filter in a system identification role.
To review the general model for system ID mode, look at System
Identification on page 4-6 for the layout.
4-15
Adaptive Filters
For the sign variations of the LMS algorithm, the examples use noise
cancellation as the demonstration application, as opposed to the system
identification application used in the LMS examples.
The input is broadband noise. For the unknown system filter, use firgr to
create a twelfth-order lowpass filter:
[b,err,res] = fircband(12,[0 0.4 0.5 1],[1 1 0 0],[1 0.2],{'w','c'});
Although you do not need them here, include the err and res output
arguments.
Now filter the signal through the unknown system to get the desired signal.
d = filter(b,1,x);
With the unknown filter designed and the desired signal in place you
construct and apply the adaptive LMS filter object to identify the unknown.
Preparing the adaptive filter object requires that you provide starting values
for estimates of the filter coefficients and the LMS step size. You could start
with estimated coefficients of some set of nonzero values; this example uses
zeros for the 12 initial filter weights.
4-16
For the step size, 0.8 is a reasonable value a good compromise between
being large enough to converge well within the 250 iterations (250 input
sample points) and small enough to create an accurate estimate of the
unknown filter.
mu = 0.8;
ha = adaptfilt.lms(13,mu);
Finally, using the adaptfilt object ha, desired signal, d, and the input to the
filter, x, run the adaptive filter to determine the unknown system and plot
the results, comparing the actual coefficients from firgr to the coefficients
found by adaptfilt.lms.
[y,e] = filter(ha,x,d);
stem([b.' ha.coefficients.'])
title('System Identification by Adaptive LMS Algorithm')
legend('Actual Filter Weights', 'Estimated Filter Weights',...
'Location', 'NorthEast')
In the stem plot the actual and estimated filter weights are the same. As an
experiment, try changing the step size to 0.2. Repeating the example with
mu = 0.2 results in the following stem plot. The estimated weights fail to
approximate the actual weights closely.
4-17
Adaptive Filters
Since this may be because you did not iterate over the LMS algorithm enough
times, try using 1000 samples. With 1000 samples, the stem plot, shown
in the next figure, looks much better, albeit at the expense of much more
computation. Clearly you should take care to select the step size with both the
computation required and the fidelity of the estimated filter in mind.
4-18
4-19
Adaptive Filters
d = filter(b,1,x);
Again d represents the desired signal d(x) as you defined it earlier and b
contains the filter coefficients for your unknown filter.
mu = 0.8;
ha = adaptfilt.nlms(13,mu);
You use the preceding code to initialize the normalized LMS algorithm.
For more information about the optional input arguments, refer to
adaptfilt.nlms in the reference section of this Users Guide.
Running the system identification process is a matter of using
adaptfilt.nlms with the desired signal, the input signal, and the initial
filter coefficients and conditions specified in s as input arguments. Then plot
the results to compare the adapted filter to the actual filter.
[y,e] = filter(ha,x,d);
stem([b.' ha.coefficients.'])
title('System Identification by Normalized LMS Algorithm')
legend('Actual Filter Weights', 'Estimated Filter Weights',...
'Location', 'NorthEast')
4-20
4-21
Adaptive Filters
4-22
When the input is zero, the new coefficients are the same as the previous set.
In vector form, the sign-data LMS algorithm is
with vector w containing the weights applied to the filter coefficients and
vector x containing the input data. e(k) (equal to desired signal - filtered
signal) is the error at time k and is the quantity the SDLMS algorithm seeks
to minimize. (mu) is the step size.
As you specify mu smaller, the correction to the filter weights gets smaller
for each sample and the SDLMS error falls more slowly. Larger mu changes
the weights more for each step so the error falls more rapidly, but the
resulting error does not approach the ideal solution as closely. To ensure good
convergence rate and stability, select mu within the following practical bounds
0<<
1
N {InputSignalPower}
4-23
Adaptive Filters
Now, add correlated white noise to signal. To ensure that the noise is
correlated, pass the noise through a lowpass FIR filter, and then add the
filtered noise to the signal.
noise=randn(1,1000);
nfilt=fir1(11,0.4); % Eleventh order lowpass filter
fnoise=filter(nfilt,1,noise); % Correlated noise data
d=signal.'+fnoise;
fnoise is the correlated noise and d is now the desired input to the sign-data
algorithm.
To prepare the adaptfilt object for processing, set the input conditions
coeffs and mu for the object. As noted earlier in this section, the values you
set for coeffs and mu determine whether the adaptive filter can remove the
noise from the signal path.
In System Identification Using adaptfilt.lms on page 4-16, you constructed
a default filter that sets the filter coefficients to zeros. In most cases that
approach does not work for the sign-data algorithm. The closer you set your
initial filter coefficients to the expected values, the more likely it is that
the algorithm remains well behaved and converges to a filter solution that
removes the noise effectively.
4-24
For this example, start with the coefficients in the filter you used to filter the
noise (nfilt), and modify them slightly so the algorithm has to adapt.
coeffs = nfilt.' -0.01; % Set the filter initial conditions.
mu = 0.05;
% Set the step size for algorithm updating.
With the required input arguments for adaptfilt.sd prepared, construct the
adaptfilt object, run the adaptation, and view the results.
ha = adaptfilt.sd(12,mu)
set(ha,'coefficients',coeffs);
[y,e] = filter(ha,noise,d);
plot(0:199,signal(1:200),0:199,e(1:200));
title('Noise Cancellation by the Sign-Data Algorithm');
legend('Actual Signal', 'Result of Noise Cancellation',...
'Location', 'NorthEast');
When adaptfilt.sd runs, it uses far fewer multiply operations than either of
the LMS algorithms. Also, performing the sign-data adaptation requires only
bit shifting multiplies when the step size is a power of two.
Although the performance of the sign-data algorithm as shown in the next
figure is quite good, the sign-data algorithm is much less stable than the
standard LMS variations. In this noise cancellation example, the signal after
processing is a very good match to the input signal, but the algorithm could
very easily grow without bound rather than achieve good performance.
Changing coeffs, mu, or even the lowpass filter you used to create the
correlated noise can cause noise cancellation to fail and the algorithm to
become useless.
4-25
Adaptive Filters
4-26
with vector w containing the weights applied to the filter coefficients and
vector x containing the input data. e(k) (equal to desired signal - filtered
signal) is the error at time k and is the quantity the SELMS algorithm seeks
to minimize. (mu) is the step size. As you specify mu smaller, the correction
to the filter weights gets smaller for each sample and the SELMS error falls
more slowly.
Larger mu changes the weights more for each step so the error falls more
rapidly, but the resulting error does not approach the ideal solution as closely.
To ensure good convergence rate and stability, select mu within the following
practical bounds
0<<
1
N {InputSignalPower}
4-27
Adaptive Filters
Now, add correlated white noise to signal. To ensure that the noise is
correlated, pass the noise through a lowpass FIR filter, then add the filtered
noise to the signal.
noise=randn(1,1000);
nfilt=fir1(11,0.4); % Eleventh order lowpass filter.
fnoise=filter(nfilt,1,noise); % Correlated noise data.
d=signal.'+fnoise;
fnoise is the correlated noise and d is now the desired input to the sign-data
algorithm.
To prepare the adaptfilt object for processing, set the input conditions
coeffs and mu for the object. As noted earlier in this section, the values you
set for coeffs and mu determine whether the adaptive filter can remove the
noise from the signal path. In System Identification Using adaptfilt.lms
on page 4-16, you constructed a default filter that sets the filter coefficients
to zeros.
Setting the coefficients to zero often does not work for the sign-error
algorithm. The closer you set your initial filter coefficients to the expected
values, the more likely it is that the algorithm remains well behaved and
converges to a filter solution that removes the noise effectively.
For this example, you start with the coefficients in the filter you used to filter
the noise (nfilt), and modify them slightly so the algorithm has to adapt.
4-28
With the required input arguments for adaptfilt.se prepared, run the
adaptation and view the results.
ha = adaptfilt.se(12,mu)
set(ha,'coefficients',coeffs);
set(ha,'persistentmemory',true); % Prevent filter reset.
[y,e] = filter(ha,noise,d);
plot(0:199,signal(1:200),0:199,e(1:200));
title('Noise Cancellation Performance by the Sign-Error LMS Algorithm');
legend('Actual Signal','Error After Noise Reduction',...
'Location','NorthEast')
Notice that you have to set the property PersistentMemory to true when you
manually change the settings of object ha.
If PersistentMemory is left to false, the default, when you try to apply
ha with the method filter, the filtering process starts by resetting the
object properties to their initial conditions at construction. To preserve the
customized coefficients in this example, you set PersistentMemory to true so
the coefficients do not get reset automatically back to zero.
When adaptfilt.se runs, it uses far fewer multiply operations than either of
the LMS algorithms. Also, performing the sign-error adaptation requires only
bit shifting multiplies when the step size is a power of two.
Although the performance of the sign-data algorithm as shown in the next
figure is quite good, the sign-data algorithm is much less stable than the
standard LMS variations. In this noise cancellation example, the signal after
processing is a very good match to the input signal, but the algorithm could
very easily become unstable rather than achieve good performance.
Changing coeffs, mu, or even the lowpass filter you used to create the
correlated noise can cause noise cancellation to fail and the algorithm to
become useless.
4-29
Adaptive Filters
4-30
where
0<<
1
N {InputSignalPower}
4-31
Adaptive Filters
Note How you set the initial conditions of the sign-sign algorithm profoundly
influences the effectiveness of the adaptation. Because the algorithm
essentially quantizes the input signal and the error signal, the algorithm
can become unstable easily.
A series of large error values, coupled with the quantization process may
result in the error growing beyond all bounds. You restrain the tendency of
the sign-sign algorithm to get out of control by choosing a small step size (<<
1) and setting the initial conditions for the algorithm to nonzero positive
and negative values.
In this noise cancellation example, adaptfilt.ss requires two input data
sets:
Data containing a signal corrupted by noise. In Using an Adaptive Filter
to Remove Noise from an Unknown System on page 4-8, this is d(k), the
desired signal. The noise cancellation process removes the noise, leaving
the cleaned signal as the content of the error signal.
Data containing random noise (x(k) in Using an Adaptive Filter to Remove
Noise from an Unknown System on page 4-8) that is correlated with the
noise that corrupts the signal data, called. Without the correlation between
the noise data, the adapting algorithm cannot remove the noise from the
signal.
For the signal, use a sine wave. Note that signal is a column vector of 1000
elements.
signal = sin(2*pi*0.055*[0:1000-1]');
Now, add correlated white noise to signal. To ensure that the noise is
correlated, pass the noise through a lowpass FIR filter, then add the filtered
noise to the signal.
noise=randn(1,1000);
nfilt=fir1(11,0.4); % Eleventh order lowpass filter
fnoise=filter(nfilt,1,noise); % Correlated noise data
d=signal.'+fnoise;
4-32
fnoise is the correlated noise and d is now the desired input to the sign-data
algorithm.
To prepare the adaptfilt object for processing, set the input conditions
coeffs and mu for the object. As noted earlier in this section, the values you
set for coeffs and mu determine whether the adaptive filter can remove the
noise from the signal path. In System Identification Using adaptfilt.lms on
page 4-16, you constructed a default filter that sets the filter coefficients to
zeros. Usually that approach does not work for the sign-sign algorithm.
The closer you set your initial filter coefficients to the expected values, the
more likely it is that the algorithm remains well behaved and converges to a
filter solution that removes the noise effectively. For this example, you start
with the coefficients in the filter you used to filter the noise (nfilt), and
modify them slightly so the algorithm has to adapt.
coeffs = nfilt.' -0.01; % Set the filter initial conditions.
mu = 0.05;
% Set the step size for algorithm updating.
With the required input arguments for adaptfilt.ss prepared, run the
adaptation and view the results.
ha = adaptfilt.ss(12,mu)
set(ha,'coefficients',coeffs);
set(ha,'persistentmemory',true); % Prevent filter reset.
[y,e] = filter(ha,noise,d);
plot(0:199,signal(1:200),0:199,e(1:200));
title('Noise Cancellation Performance of the Sign-Sign LMS Algorithm');
legend('Actual Signal', 'Error After Noise Reduction', ...
'Location', 'NorthEast');
Notice that you have to set the property PersistentMemory to true when you
manually change the settings of object ha.
If PersistentMemory is left to false, when you try to apply ha with the
method filter the filtering process starts by resetting the object properties to
their initial conditions at construction. To preserve the customized coefficients
in this example, you set PersistentMemory to true so the coefficients do not
get reset automatically back to zero.
4-33
Adaptive Filters
When adaptfilt.ss runs, it uses far fewer multiply operations than either of
the LMS algorithms. Also, performing the sign-sign adaptation requires only
bit shifting multiplies when the step size is a power of two.
Although the performance of the sign-sign algorithm as shown in the next
figure is quite good, the sign-sign algorithm is much less stable than the
standard LMS variations. In this noise cancellation example, the signal after
processing is a very good match to the input signal, but the algorithm could
very easily become unstable rather than achieve good performance.
Changing coeffs, mu, or even the lowpass filter you used to create the
correlated noise can cause noise cancellation to fail and the algorithm to
become useless.
4-34
4-35
Adaptive Filters
One interesting input option that applies to RLS algorithms is not present
in the LMS processes a forgetting factor, , that determines how the
algorithm treats past data input to the algorithm.
When the LMS algorithm looks at the error to minimize, it considers only the
current error value. In the RLS method, the error considered is the total error
from the beginning to the current data point.
Said another way, the RLS algorithm has infinite memory all error data is
given the same consideration in the total error. In cases where the error value
might come from a spurious input data point or points, the forgetting factor
lets the RLS algorithm reduce the value of older error data by multiplying
the old data by the forgetting factor.
Since 0 < 1, applying the factor is equivalent to weighting the older error.
When = 1, all previous error is considered of equal weight in the total error.
As approaches zero, the past errors play a smaller role in the total. For
example, when = 0.9, the RLS algorithm multiplies an error value from 50
samples in the past by an attenuation factor of 0.950 = 5.15 x 10-3, considerably
deemphasizing the influence of the past error on the current total error.
Unknown System
d(k)
x(k)
4-36
Adaptive Filter
text
y(k)
+
_ SUM
e(k)
Cascading the adaptive filter with the unknown filter causes the adaptive
filter to converge to a solution that is the inverse of the unknown system.
If the transfer function of the unknown is H(z) and the adaptive filter
transfer function is G(z), the error measured between the desired signal
and the signal from the cascaded system reaches its minimum when the
product of H(z) and G(z) is 1, G(z)*H(z) = 1. For this relation to be true,
G(z) must equal 1/H(z), the inverse of the transfer function of the unknown
system.
To demonstrate that this is true, create a signal to input to the cascaded
filter pair.
x = randn(1,3000);
In the cascaded filters case, the unknown filter results in a delay in the signal
arriving at the summation point after both filters. To prevent the adaptive
filter from trying to adapt to a signal it has not yet seen (equivalent to
predicting the future), delay the desired signal by 32 samples, the order of
the unknown system.
Generally, you do not know the order of the system you are trying to identify.
In that case, delay the desired signal by the number of samples equal to half
the order of the adaptive filter. Delaying the input requires prepending 12
zero-values samples to x.
delay = zeros(1,12);
d = [delay x(1:2988)]; % Concatenate the delay and the signal.
You have to keep the desired signal vector d the same length as x, hence
adjust the signal element count to allow for the delay samples.
Although not generally true, for this example you know the order of the
unknown filter, so you add a delay equal to the order of the unknown filter.
For the unknown system, use a lowpass, 12th-order FIR filter.
ufilt = fir1(12,0.55,'low');
Filtering x provides the input data signal for the adaptive algorithm function.
4-37
Adaptive Filters
xdata = filter(ufilt,1,x);
To set the input argument values for the adaptfilt.rls object, use the
constructor adaptfilt.rls, providing the needed arguments l, lambda, and
invcov.
For more information about the input conditions to prepare the RLS algorithm
object, refer to adaptfilt.rls in the reference section of this users guide.
p0 = 2*eye(13);
lambda = 0.99;
ha = adaptfilt.rls(13,lambda,p0);
Most of the process to this point is the same as the preceding examples.
However, since this example seeks to develop an inverse solution, you need to
be careful about which signal carries the data and which is the desired signal.
Earlier examples of adaptive filters use the filtered noise as the desired
signal. In this case, the filtered noise (xdata) carries the unknown system
information. With Gaussian distribution and variance of 1, the unfiltered
noise d is the desired signal. The code to run this adaptive filter example is
[y,e] = filter(ha,xdata,d);
where y returns the coefficients of the adapted filter and e contains the error
signal as the filter adapts to find the inverse of the unknown system. You can
review the returned elements of the adapted filter in the properties of ha.
The next figure presents the results of the adaptation. In the figure, the
magnitude response curves for the unknown and adapted filters show. As a
reminder, the unknown filter was a lowpass filter with cutoff at 0.55, on the
normalized frequency scale from 0 to 1.
4-38
Magnitude (dB)
50
50
100
Inverse Filter
Unknown System
150
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
Phase (degrees)
200
400
600
800
1000
1200
Viewed alone (refer to the following figure), the inverse system looks like a
fair compensator for the unknown lowpass filter a high pass filter with
linear phase.
4-39
Adaptive Filters
Magnitude (dB)
30
20
10
0
10
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Normalized Frequency ( rad/sample)
0.8
0.9
Phase (degrees)
200
400
600
800
1000
1200
4-40
4-41
Adaptive Filters
a reference signal
a noisy signal that contains both the desired signal and an added noise
component.
where s is the desired signal and the noise is v1. Adaptive filter processing
seeks to recover s from x by removing v1. To complete the signals needed to
perform adaptive filtering, the adaptation process requires a reference signal.
4-42
hlms = adaptfilt.lms(7);
hnlms = adaptfilt.nlms(7);
mumaxmselms =
0.1261
4-43
Adaptive Filters
If you know the step size to use, you can set the step size value with the step
input argument when you create your filter.
hlms = adaptfilt.lms(N,step); Adds the step input argument.
4-44
As a reference point, include the noisy signal as a dotted line in the plot.
hold on
plot(n(900:end),x(900:end),'k:')
xlabel('Time index (n)');
ylabel('Amplitude');
hold off
4-45
Adaptive Filters
4-46
0.8879
0.1359
0.0036
0.0023
0.0810
0.0184
-0.0001
1.0712
0.4070
0.1539
0.0549
0.1098
0.0521
0.0041
To keep the history of the filter when filtering a new set of data, enable
persistent memory for the filter by setting the PersistentMemory property
to true. In this configuration, the filter uses the final states and coefficients
from the previous run as the initial conditions for the next run and set of data.
[ylms,elms] = filter(hlms,v2,x);
hlms.PersistentMemory = true;
[ylms2,elms2] = filter(hlms,v2,x); % No longer the same
Setting the property value to true is useful when you are filtering large
amounts of data that you partition into smaller sets and then feed into the
filter using a for-loop construction.
4-47
Adaptive Filters
In the next plot you see the calculated learning curves for the LMS and
NLMS adaptive filters.
4-48
4-49
4-50
Adaptive Filters
4-51
Adaptive Filters
2 Copy and paste the subsystem called Acoustic Environment into a new
model.
3 Double-click the Acoustic Environment subsystem.
Gaussian noise is used to create the signal sent to the Exterior Mic output
port. If the input to the Filter port changes from 0 to 1, the Digital Filter
block changes from a lowpass filter to a bandpass filter. The filtered noise
4-52
output from the Digital Filter block is added to signal coming from a .wav
file to produce the signal sent to the Pilots Mic output port.
You have now created an acoustic environment. In the following topics, you
use this acoustic environment to produce a model capable of adaptive noise
cancellation.
on page 4-51 is not open on your desktop, you can open an equivalent
model by typing
ex_adapt1_audio
Adaptive Filters library, click-and-drag an LMS Filter block into the model
that contains the Acoustic Environment subsystem.
3 Double-click the LMS Filter block. Set the block parameters as follows,
4-53
Adaptive Filters
The block uses the normalized LMS algorithm to calculate the forty filter
coefficients. Setting the Leakage factor (0 to 1) parameter to 1 means
that the current filter coefficient values depend on the filters initial
conditions and all of the previous input values.
4 Click-and-drag the following blocks into your model.
Block
Library
Quantity
Constant
Simulink/Sources
Manual Switch
Simulink/Signal Routing
Terminator
Simulink/Sinks
Downsample
Signal Operations
To Audio Device
Sinks
Waterfall Scope
Sinks
5 Connect the blocks so that your model resembles the following figure.
4-54
4-55
Adaptive Filters
The filter weights are being updated so often that there is very little change
from one update to the next. To see a more noticeable change, you need to
downsample the output from the Wts port.
8 Double-click the Waterfall Scope block. The Waterfall scope window opens.
9 Click the Scope parameters button.
4-56
Y Min = -0.188
Y Max = 0.179
11 Click the Data history tab. Set the parameters as follows:
History traces = 50
Data logging = All visible
12 Close the Parameters window leaving all other parameters at their
default values.
You might need to adjust the axes in the Waterfall scope window in order
to view the plots.
13 Click the Fit to view button in the Waterfall scope window. Then,
4-57
Adaptive Filters
You can also listen to the simulation using the speakers attached to your
computer.
16 Experiment with changing the Manual Switch so that the input to the
4-58
You have now created a model capable of adaptive noise cancellation. The
adaptive filter in your model is able to filter out both low frequency noise and
noise within a frequency range. In the next topic, Modify Adaptive Filter
Parameters During Model Simulation on page 4-59, you modify the LMS
Filter block and change its parameters during simulation.
on page 4-51 is not open on your desktop, you can open an equivalent
model by typing
ex_adapt2_audio
4-59
Adaptive Filters
Step-size, Adapt, and Reset ports appear on the LMS Filter block.
4-60
Block
Library
Quantity
Constant
Simulink/Sources
Manual Switch
Simulink/Signal Routing
4-61
4-62
Adaptive Filters
You can also listen to the simulation using the speakers attached to your
computer.
12 Double-click the Manual Switch block so that the input to the Acoustic
4-63
Adaptive Filters
is 1.
The block resets the filter weights to their initial values. In the Block
Parameters: LMS Filter dialog box, from the Reset port list, you chose
Non-zero sample. This means that any nonzero input to the Reset port
triggers a reset operation.
You have now experimented with adaptive noise cancellation using the LMS
Filter block. You adjusted the parameters of your adaptive filter and viewed
the effects of your changes while the model was running.
For more information about adaptive filters, see the following block reference
pages:
LMS Filter
RLS Filter
Block LMS Filter
Fast Block LMS Filter
4-64
Adaptive Filtering
Examples
lmsadeq
lmsadtde
Nonstationary Channel
Estimation
dspchanest
rlsdemo
4-65
Adaptive Filters
Selected Bibliography
[1] Hayes, Monson H., Statistical Digital Signal Processing and Modeling,
John Wiley & Sons, 1996, 493552.
[2] Haykin, Simon, Adaptive Filter Theory, Prentice-Hall, Inc., 1996
4-66
5
Multirate and Multistage
Filters
Learn how to analyze, design, and implement multirate and multistage filters
in MATLAB and Simulink.
Multirate Filters on page 5-2
Multistage Filters on page 5-6
Example Case for Multirate/Multistage Filters on page 5-8
Filter Banks on page 5-12
Multirate Filtering in Simulink on page 5-21
Multirate Filters
In this section...
Why Are Multirate Filters Needed? on page 5-2
Overview of Multirate Filters on page 5-2
5-2
Multirate Filters
If you start with the top signal, sampled at a frequency Fs, then the bottom
signal is sampled at Fs/2 frequency. In this case, the decimation factor, or M,
is 2.
The following figure illustrates effect of decimation in the frequency domain.
5-3
In the first graphic in the figure you can see a signal that is critically sampled,
i.e. the sample rate is equal to two times the highest frequency component
of the sampled signal. As such the period of the signal in the frequency
domain is no greater than the bandwidth of the sampling frequency. When
reduce the sampling frequency (decimation), aliasing can occur, where the
magnitudes at the frequencies near the edges of the original period become
indistinguishable, and the information about these values becomes lost. To
work around this problem, the signal can be filtered before the decimation
process, avoiding overlap of the signal spectra at Fs/2.
5-4
Multirate Filters
If you wish to decimate a signal which does not meet the frequency criteria,
you can either:
5-5
Multistage Filters
In this section...
Why Are Multistage Filters Needed? on page 5-6
Optimal Multistage Filters in DSP System Toolbox on page 5-6
5-6
Multistage Filters
done automatically. Not only does DSP System Toolbox software determine
the optimal number of stages, but it also optimizes the total filter solution.
5-7
Example Overview
This example shows the efficiency gains that are possible when using
multirate and multistage filters for certain applications. In this case a distinct
advantage is achieved over regular linear-phase equiripple design when a
narrow transition-band width is required. A more detailed treatment of the
key points made here can be found in the example entitled Efficient Narrow
Transition-Band FIR Filter Design.
% Passband edge
Fstop = 0.14;
% Stopband edge
Rpass = 0.001;
5-8
When you determine the cost of this design, you can see that 695 multipliers
are required.
cost(Hd)
You can then view the cost of the filter created using this design step, and you
can see that a significant cost advantage has been achieved.
cost(Hd_multi)
5-9
Notice that the stopband attenuation for the multistage design is about twice
that of the other designs. This is because the decimators must attenuate
out-of-band components by 66 dB in order to avoid aliasing that would violate
the specifications. Similarly, the interpolators must attenuate images by
66 dB. You can also see that the passband gain for this design is no longer
0 dB, because each interpolator has a nominal gain (in linear units) equal
to its interpolation factor, and the total interpolation factor for the three
interpolators is 6.
5-10
= 0:1799;
= sin(0.1*pi*n') + 2*sin(0.15*pi*n');
= filter(Hd,x);
y_multi = filter(Hd_multi,x);
[Pxx,w]
= periodogram(x);
Pyy
= periodogram(y);
Pyy_multi = periodogram(y_multi);
plot(w/pi,10*log10([Pxx,Pyy,Pyy_multi]));
xlabel('Normalized Frequency (x\pi rad/sample)');
ylabel('Power density (dB/rad/sample)');
legend('Input signal PSD','Equiripple output PSD',...
'Multirate/multistage output PSD')
axis([0 1 -50 30])
grid on
5-11
Filter Banks
Multirate filters alter the sample rate of the input signal during the filtering
process. Such filters are useful in both rate conversion and filter bank
applications.
The Dyadic Analysis Filter Bank block decomposes a broadband signal into a
collection of subbands with smaller bandwidths and slower sample rates. The
Dyadic Synthesis Filter Bank block reconstructs a signal decomposed by the
Dyadic Analysis Filter Bank block.
To use a dyadic synthesis filter bank to perfectly reconstruct the output of a
dyadic analysis filter bank, the number of levels and tree structures of both
filter banks must be the same. In addition, the filters in the synthesis filter
bank must be designed to perfectly reconstruct the outputs of the analysis
filter bank. Otherwise, the reconstruction will not be perfect.
Each unit consists of a lowpass (LP) and highpass (HP) FIR filter pair,
followed by a decimation by a factor of 2. The filters are halfband filters with
a cutoff frequency of Fs / 4, a quarter of the input sampling frequency. Each
filter passes the frequency band that the other filter stops.
The unit decomposes its input into adjacent high-frequency and low-frequency
subbands. Compared to the input, each subband has half the bandwidth (due
to the half-band filters) and half the sample rate (due to the decimation by 2).
5-12
Filter Banks
Note The following figures illustrate the concept of a filter bank, but not how
the block implements a filter bank; the block uses a more efficient polyphase
implementation.
Use the above figure and the following figure to compare the two tree
structures of the dyadic analysis filter bank. Note that the asymmetric
structure decomposes only the low-frequency output from each level, while
the symmetric structure decomposes the high- and low-frequency subbands
output from each level.
5-13
5-14
Filter Banks
The following table summarizes the key characteristics of the symmetric and
asymmetric dyadic analysis filter bank.
Notable Characteristics of Asymmetric and Symmetric Dyadic Analysis Filter Banks
Characteristic
N-Level Symmetric
N-Level Asymmetric
Low- and
High-Frequency
Subband
Decomposition
Number of Output
Subbands
2n
n+1
Bandwidth and
Number of Samples
in Output Subbands
BW / 2k
BWk =
n
BW / 2
(1 k n)
(k = n + 1)
N / 2
(1 k n)
Nk =
n
(k = n + 1)
N / 2
The bandwidth of, and number of samples in
each subband (except the last) is half those of
the previous subband. The last two subbands
have the same bandwidth and number of
samples since they originate from the same
level in the filter bank.
k
5-15
N-Level Symmetric
N-Level Asymmetric
Output Sample
Period
Wavelet
Applications
Each unit consists of a lowpass (LP) and highpass (HP) FIR filter pair,
preceded by an interpolation by a factor of 2. The filters are halfband filters
with a cutoff frequency of Fs / 4, a quarter of the input sampling frequency.
Each filter passes the frequency band that the other filter stops.
5-16
Filter Banks
Use the above figure and the following figure to compare the two tree
structures of the dyadic synthesis filter bank. Note that in the asymmetric
structure, the low-frequency subband input to each level is the output of
the previous level, while the high-frequency subband input to each level is
an input to the filter bank. In the symmetric structure, both the low- and
high-frequency subband inputs to each level are outputs from the previous
level.
5-17
5-18
Filter Banks
N-Level Symmetric
N-Level Asymmetric
Input Paths
Through the
Filter Bank
Number of Input
Subbands
2n
n+1
Bandwidth
and Number of
Samples in Input
Subbands
BW / 2k
BWk =
n
BW / 2
N / 2k
Nk =
n
N / 2
Input Sample
Periods
(1 k n)
(k = n + 1)
(1 k n)
(k = n + 1)
2k (Tso ) (1 k n)
=
n
2 (Tso ) ( k = n + 1)
where the output sample period is Tso.
5-19
N-Level Symmetric
N-Level Asymmetric
Total Number of
Input Samples
The number of samples in the output is always equal to the total number
of samples in all of the input subbands.
Wavelet
Applications
5-20
Description
Command for
Opening Examples
in MATLAB
Audio Sample
Rate Conversion
dspaudiosrc
Sigma-Delta A/D
Converter
dspsdadc
Wavelet
Reconstruction
and Noise
Reduction
dspwavelet
5-21
5-22
6
Transforms, Estimation,
and Spectral Analysis
Learn about transforms, estimation and spectral analysis.
Transform Time-Domain Data into Frequency Domain on page 6-2
Transform Frequency-Domain Data into Time Domain on page 6-7
Linear and Bit-Reversed Output Order on page 6-13
Calculate Channel Latencies Required for Wavelet Reconstruction on
page 6-15
Spectral Analysis on page 6-24
Power Spectrum Estimates on page 6-25
Spectrograms on page 6-36
u = sin ( 30 t ) + sin ( 80 t )
Then, you transform this sinusoid into the frequency domain using an FFT
block:
1 At the MATLAB command prompt, type ex_fft_tut.
6-2
2 Double-click the Sine Wave block. The Block Parameters: Sine Wave
Amplitude = 1
Frequency = [15 40]
Phase offset = 0
6-3
This block takes the complex output of the FFT block and converts this
output to magnitude.
9 Double-click the Vector Scope block.
10 Set the block parameters as follows, and then click OK:
6-4
You have now transformed two sinusoidal signals from the time domain to
the frequency domain.
6-5
6-6
6-7
2 Double-click the Sine Wave block. The Block Parameters: Sine Wave
Amplitude = 1
Frequency = [15 40]
Phase offset = 0
6-8
opens.
8 Select the Output in bit-reversed order check box., and then click OK.
9 Double-click the IFFT block. The Block Parameters: IFFT dialog box
opens.
10 Set the block parameters as follows, and then click OK:
6-9
The flat line on the scope suggests that there is no difference between the
original signal and the estimate of the original signal. Therefore, the IFFT
6-10
6-11
In actuality, the two signals are identical to within round-off error. The
previous figure shows the enlarged trace. The differences between the
two signals is on the order of 10-15.
6-12
binary representation.
3 Translate the indices back to their decimal representation.
6-13
The next diagram illustrates the linear and bit-reversed outputs of the FFT
block. The output values are the same, but they appear in different order.
6-14
6-15
Before you can begin calculating the latencies required for perfect wavelet
reconstruction, you must know the types of filters being used in your model.
The Dyadic Analysis Filter Bank and the Dyadic Synthesis Filter Bank blocks
in the ex_wavelets model have the following settings:
Filter = Biorthogonal
Filter order [synthesis/analysis] = [3/5]
Number of levels = 3
Tree structure = Asymmetric
Input = Multiple ports
6-16
Based on these settings, the Dyadic Analysis Filter Bank and the Dyadic
Synthesis Filter Bank blocks construct biorthogonal filters using the Wavelet
Toolbox wfilters function.
Where Lo_D and Hi_D represent the low- and high-pass filters used by the
Dyadic Analysis Filter Bank block, and Lo_R and Hi_R represent the low- and
high-pass filters used by the Dyadic Synthesis Filter Bank block.
After you construct the filters in the MATLAB workspace, you can use
fvtool to determine the group delay of the filters. To analyze the low-pass
biorthogonal filter used by the Dyadic Analysis Filter Bank block, you must
do the following:
Type fvtool(Lo_D) at the MATLAB command line to launch the Filter
Visualization Tool.
When the Filter Visualization Tool opens, click the Group delay response
) on the toolbar, or select Group Delay Response from the
button (
Analysis menu.
Based on the Filter Visualization Tools analysis, you can see that the group
delay of the Dyadic Analysis Filter Bank blocks low-pass biorthogonal filter is
5.5.
6-17
6-18
Note Repeat this procedure to analyze the group delay of each of the filters
in your model. This section does not show the results for each filter in the
ex_wavelets model because all wavelet filters in this particular example
have the same group delay.
F1
F0
F1
F0
F0
F1
F0
F0
F0
G1
Path 4
G1
G0
Path 3
G1
G0
G0
Path 2
G0
G0
G0
Path 1
Delay M
6-19
The extra delay values of M and N on paths 3 and 4 in the previous figure
ensure that the total delay on each of the four filter paths is identical.
Equivalent to
z-1
z-1
z-2
Equivalent to
You can apply the Noble identities by summing the delay on each signal path
from right to left. The first Noble identity indicates that moving a delay of 1
before a downsample of 2 is equivalent to multiplying that delay value by 2.
Similarly, the second Noble identity indicates that moving a delay of 2 before
an upsample of 2 is equivalent to dividing that delay value by 2.
The fvtool analysis in step 1 found that both the low- and high-pass filters of
the analysis filter bank have the same group delay (F0 = F1 = 5.5). Thus, you
can use F to represent the group delay of the analysis filter bank. Similarly,
the group delay of the low- and high-pass filters of the synthesis filter bank is
the same (G0=G1=5.5), so you can use G to represent the group delay of the
synthesis filter bank.
The following figure shows the filter bank system with the intermediate delay
sums displayed below each path.
6-20
2N+(F+G)
Delay N
2N+G
F
N+0.5G
F
7(F+G)
6F+7G
F
7(F+G)
3F+3.5G
6F+7G
3F+3.5G
Delay M
0.75G
2
0.875G
2
0.875G
1.75G
2
1.75G
1.5G
0.75G
0.5G
1.5G
Path 4
Path 3
Path 2
Path 1
1.5G
G
2
0.5G
G
0.75G
G
2
M+0.75G
0.5G
G
2
0.5G
You can see from the previous figure that the signal delays on paths 1 and
2 are identical: 7(F+G). Because each path of the filter bank system has
identical delay, you can equate the delay equations for paths 3 and 4 with the
delay equation for paths 1 and 2. After constructing these equations, you
can solve for M and N, respectively:
Path 3 = Path 1 4 M + 3( F + G) = 7( F + G)
M = F+G
Path 4 = Path 1 2 N + ( F + G) = 7( F + G)
N = 3( F + G)
The fvtool analysis in step 1 found the group delay of each biorthogonal
wavelet filter in this model to be 5.5 samples. Therefore, F = 5.5 and G =
5.5. By inserting these values into the two previous equations, you get M =
11 and N = 33. Because the total delay on each filter path must be the same,
you can find the overall delay of the filter bank system by inserting F = 5.5
6-21
and G = 5.5 into the delay equation for any of the four filter paths. Inserting
the values of F and G into 7(F+G) yields an overall delay of 77 samples for
the filter bank system of the ex_wavelets model.
After you run the model, examine the reconstruction error in the Difference
scope. To further examine any particular areas of interest, use the zoom tools
available on the toolbar of the scope window or from the View menu.
6-22
References
[1] Strang, G. and Nguyen, T. Wavelets and Filter Banks. Wellesley, MA:
Wellesley-Cambridge Press, 1996.
6-23
Spectral Analysis
The Power Spectrum Estimation library provides a number of blocks for
spectral analysis. Many of them have correlates in Signal Processing Toolbox
software, which are shown in parentheses:
Burg Method (pburg)
Covariance Method (pcov)
Magnitude FFT (periodogram)
Modified Covariance Method (pmcov)
Short-Time FFT
Yule-Walker Method (pyulear)
See Spectral Analysis in the Signal Processing Toolbox documentation for
an overview of spectral analysis theory and a discussion of the above methods.
DSP System Toolbox software provides two examples that illustrate the
spectral analysis blocks:
A Comparison of Spectral Analysis Techniques (dspsacomp)
Spectral Analysis: Short-Time FFT (dspstfft)
6-24
Library
Sources
Buffer
Periodogram
Vector Scope
Sinks
6-25
Once you have assembled the blocks needed to calculate the power spectrum
of your speech signal, you can set the block parameters.
6-26
2 Load the speech signal into the MATLAB workspace by typing load mtlb
the MATLAB workspace into your Simulink model. Open the Signal
From Workspace dialog box by double-clicking the block. Set the block
parameters as follows:
Signal = mtlb
Sample time = 1/8000
Samples per frame = 80
Form output after final data value by = Setting to zero
Once you are done setting these parameters, the Signal From Workspace
dialog box should look similar to the figure below. Click OK to apply your
changes.
6-27
samples. Open the Buffer dialog box by double-clicking the block. Set the
block parameters as follows:
Output buffer size (per channel) = 128
6-28
Buffer overlap = 48
Initial conditions = 0
Treat Mx1 and unoriented sample-based signals as = One channel
Once you are done setting these parameters, the Buffer dialog box should
look similar to the figure below. Click OK to apply your changes.
power spectrum of the speech signal. Open the Periodogram dialog box by
double-clicking the block and set the block parameters as follows:
6-29
6-30
time. The length of the FFT is assumed to be 128, which is the number of
samples per frame being output from the Buffer block.
6 Use the Vector Scope block to view the power spectrum of the speech signal.
Open the Vector Scope dialog box by double-clicking the block. Set the
block parameters as follows:
Input domain = Frequency
Click the Axis Properties tab.
Clear the Inherit sample time from input check box.
Sample time of original time series = 1/8000
Y-axis label = Magnitude-squared, dB
Once you are done setting these parameters, the Axis Properties pane
of the Vector Scope dialog box should look similar to the figure below. As
you can see by the Y-axis scaling parameter, the decibel amplitude is
plotted in a vector scope window.
6-31
Because you are buffering the input with a nonzero overlap, you have
altered the sample time of the signal. As a result, you need to specify the
6-32
sample time of the original time series. Otherwise, the overlapping buffer
samples lead the block to believe that the sample time is shorter than it
actually is.
After you have set the block parameter values, you can calculate and view the
power spectrum of the speech signal.
6-33
box by clicking OK. These parameters are saved only when you save your
model.
4 If you have not already done so, load the speech signal into the MATLAB
6-34
During the simulation, the Vector Scope window displays a series of frames
output from the Periodogram block. Each of these frames corresponds to
a window of the original speech signal. The data in each frame represents
the power spectrum, or contribution of every frequency to the power of the
original speech signal, for a given window.
In the next section, Spectrograms on page 6-36, you use these power spectra
to create a spectrogram of the speech signal.
6-35
Spectrograms
In this section...
Modify the Block Diagram on page 6-36
Set the Model Parameters on page 6-38
View the Spectrogram of the Speech Signal on page 6-43
page 6-33 is not open on your desktop, you can open an equivalent model
by typing
ex_gstut11
6-36
Spectrograms
2 Add the following blocks to your model. Subsequent topics describe how
Library
Selector
dB Conversion
Buffer
Reshape
Matrix Viewer
Sinks
3 Connect the blocks as shown in the figure below. These blocks extract the
6-37
Once you have assembled the blocks needed to view the spectrogram of your
speech signal, you can set the block parameters.
6-38
Spectrograms
2 Use the Selector block to extract the first 64 elements, or the positive
6-39
3 The dB Conversion block converts the magnitude of the input FFT signal to
Open the Buffer1 dialog box by double-clicking the block. Set the block
parameters as follows:
Output buffer size (per channel) = 64*48
Buffer overlap = 64*46
Initial conditions = -70
Treat Mx1 and unoriented sample-based signals as = One channel
Once you are done setting these parameters, the Buffer1 dialog box should
look similar to the following figure. To apply your changes, click OK.
Setting the value of the Buffer overlap parameter slightly less than
the value of the Output buffer size (per channel) parameter ensures
that your spectrogram represents smooth movement through time. The
6-40
Spectrograms
signal. Open the Matrix Viewer dialog box by double-clicking the block.
Set the block parameters as follows:
Click the Image Properties tab.
Colormap matrix = jet(256)
Minimum input value = -150
Maximum input value = -65
Select the Display colorbar check box.
Once you are done setting these parameters, the Image Properties pane
should look similar to the figure below.
6-41
6-42
Spectrograms
After you have set the parameter values, you can calculate and view the
spectrogram of the speech signal.
6-43
2 Run the model. During the simulation, the Vector Scope window displays a
sequence of power spectrums, one for each window of the original speech
signal. The power spectrum is the contribution of every frequency to the
power of the speech signal.
6-44
Spectrograms
6-45
In this example, you viewed the spectrogram of your speech signal using a
Matrix Viewer block. You can find additional DSP System Toolbox product
examples in the Help browser. To access these examples, click the Contents
tab, double-click DSP System Toolbox, and then click Examples. A list of
the examples in the DSP System Toolbox documentation appears in the right
pane of the Help browser.
6-46
7
Mathematics
Learn about statistics and linear algebra.
Statistics on page 7-2
Linear Algebra and Least Squares on page 7-6
Mathematics
Statistics
In this section...
Statistics Blocks on page 7-2
Basic Operations on page 7-3
Running Operations on page 7-4
Statistics Blocks
The Statistics library provides fundamental statistical operations such as
minimum, maximum, mean, variance, and standard deviation. Most blocks in
the Statistics library support two types of operations; basic and running.
The blocks listed below toggle between basic and running modes using the
Running check box in the parameter dialog box:
Histogram
Mean
RMS
Standard Deviation
Variance
An unselected Running check box means that the block is operating in
basic mode, while a selected Running box means that the block is operating
in running mode.
The Maximum and Minimum blocks are slightly different from the blocks
above, and provide a Mode parameter in the block dialog box to select the
type of operation. The Value and Index, Value, and Index options in the
Mode menu all specify basic operation, in each case enabling a different set
of output ports on the block. The Running option in the Mode menu selects
running operation.
7-2
Statistics
Basic Operations
A basic operation is one that processes each input independently of previous
and subsequent inputs. For example, in basic mode (with Value and Index
selected, for example) the Maximum block finds the maximum value in each
column of the current input, and returns this result at the top output (Val).
Each consecutive Val output therefore has the same number of columns as
the input, but only one row. Furthermore, the values in a given output only
depend on the values in the corresponding input. The block repeats this
operation for each successive input.
This type of operation is exactly equivalent to the MATLAB command
val = max(u)
The Buffer blocks Buffer size (Mo) parameter determines the size of the
window. The Buffer overlap (L) parameter defines the slide factor for
the window. At each sample instant, the window slides by Mo-L points. The
Buffer overlap is often Mo-1, so that a new statistic is computed for every
new signal sample.
7-3
Mathematics
Running Operations
A running operation is one that processes successive inputs, and computes
a result that reflects both current and past inputs. In this mode, you must
use the Input processing parameter to specify whether the block performs
sample- or frame-based processing on the inputs. A reset port enables you
to restart this tracking at any time. The running statistic is computed for
each input channel independently, so the blocks output is the same size as
the input.
For example, in running mode (Running selected from the Mode parameter)
the Maximum block outputs a record of the inputs maximum value over time.
7-4
Statistics
7-5
Mathematics
7-6
1 2 3
A = 4 0 6 b =
2 1 3
1
2
1
You can verify the solution by using the Matrix Multiply block to perform the
multiplication Ax, as shown in the following ex_matrixmultiply_tut1 model.
7-7
Mathematics
Matrix Factorizations
The Matrix Factorizations library provides the following blocks for factoring
various kinds of matrices:
Cholesky Factorization
LDL Factorization
LU Factorization
QR Factorization
Singular Value Decomposition
Some of the blocks offer particular strengths for certain classes of problems.
For example, the Cholesky Factorization block is particularly suited to
factoring a Hermitian positive definite matrix into triangular components,
whereas the QR Factorization is particularly suited to factoring a rectangular
matrix into unitary and upper triangular components.
7-8
Ap
4 0 6
= 1 2 3
2 1 3
6
0 0
4 0
1
U = 0 2 1.5 L = 0.25 1 0
0 0 0.75
0.5 0.5 1
You can check that LU = Ap with the Matrix Multiply block, as shown in the
following ex_matrixmultiply_tut2 model.
Matrix Inverses
The Matrix Inverses library provides the following blocks for inverting various
kinds of matrices:
Cholesky Inverse
LDL Inverse
7-9
Mathematics
LU Inverse
Pseudoinverse
1 2 3
A = 4 0 6
2 1 3
and then forms the product A-1A, which yields the identity matrix of order 3,
as expected.
7-10
0.5
2
1
0 .5
= 0
1
0.6667 0.5 1.333
8
Fixed-Point Design
Learn about fixed-point data types and how to convert floating-point models
to fixed-point.
Fixed-Point Signal Processing on page 8-2
Fixed-Point Concepts and Terminology on page 8-4
Arithmetic Operations on page 8-10
Fixed-Point Support for MATLAB System Objects on page 8-21
Specify Fixed-Point Attributes for Blocks on page 8-28
Quantizers on page 8-52
Fixed-Point Filter Design on page 8-68
Fixed-Point Design
Fixed-Point Features
Many of the blocks in this product have fixed-point support, so you can design
signal processing systems that use fixed-point arithmetic. Fixed-point support
in DSP System Toolbox software includes
Signed twos complement and unsigned fixed-point data types
Word lengths from 2 to 128 bits in simulation
Word lengths from 2 to the size of a long on the Simulink Coder C
code-generation target
Overflow handling and rounding methods
C code generation for deployment on a fixed-point embedded processor,
with Simulink Coder code generation software. The generated code uses all
allowed data types supported by the embedded target, and automatically
includes all necessary shift and scaling operations
8-2
8-3
Fixed-Point Design
Note The Glossary defines much of the vocabulary used in these sections.
For more information on these subjects, see the Fixed-Point Designer
documentation.
8-4
where
bi is the ith binary digit.
wl is the word length in bits.
bwl1 is the location of the most significant, or highest, bit (MSB).
b0 is the location of the least significant, or lowest, bit (LSB).
The binary point is shown four places to the left of the LSB. In this
example, therefore, the number is said to have four fractional bits, or a
fraction length of four.
Fixed-point data types can be either signed or unsigned. Signed binary
fixed-point numbers are typically represented in one of three ways:
Sign/magnitude
Ones complement
Twos complement
Twos complement is the most common representation of signed fixed-point
numbers and is used by System Toolbox software. See Twos Complement
on page 8-11 for more information.
Scaling
Fixed-point numbers can be encoded according to the scheme
8-5
Fixed-Point Design
The slope and bias together represent the scaling of the fixed-point number.
In a number with zero bias, only the slope affects the scaling. A fixed-point
number that is only scaled by binary point position is equivalent to a number
in the Fixed-Point Designer [Slope Bias] representation that has a bias equal
to zero and a slope adjustment equal to one. This is referred to as binary
point-only scaling or power-of-two scaling:
Range
The range is the span of numbers that a fixed-point data type and scaling
can represent. The range of representable numbers for a twos complement
fixed-point number of word length wl, scaling S, and bias B is illustrated
below:
8-6
For both signed and unsigned fixed-point numbers of any data type, the
number of different bit patterns is 2wl.
For example, in twos complement, negative numbers must be represented
as well as zero, so the maximum value is 2wl1. Because there is only one
representation for zero, there are an unequal number of positive and negative
numbers. This means there is a representation for -2wl1 but not for 2wl 1:
Precision
The precision of a fixed-point number is the difference between successive
values representable by its data type and scaling, which is equal to the value
8-7
Fixed-Point Design
of its least significant bit. The value of the least significant bit, and therefore
the precision of the number, is determined by the number of fractional bits.
A fixed-point value can be represented to within half of the precision of its
data type and scaling.
For example, a fixed-point representation with four bits to the right of the
binary point has a precision of 2-4 or 0.0625, which is the value of its least
significant bit. Any number within the range of this data type and scaling can
be represented to within (2-4)/2 or 0.03125, which is half the precision. This is
an example of representing a number with finite precision.
Rounding Modes. When you represent numbers with finite precision,
not every number in the available range can be represented exactly. If a
number cannot be represented exactly by the specified data type and scaling,
it is rounded to a representable number. Although precision is always lost
in the rounding operation, the cost of the operation and the amount of bias
that is introduced depends on the rounding mode itself. To provide you with
greater flexibility in the trade-off between cost and bias, DSP System Toolbox
software currently supports the following rounding modes:
Ceiling rounds the result of a calculation to the closest representable
number in the direction of positive infinity.
Convergent rounds the result of a calculation to the closest representable
number. In the case of a tie, Convergent rounds to the nearest even
number. This is the least biased rounding mode provided by the toolbox.
Floor, which is equivalent to truncation, rounds the result of a calculation
to the closest representable number in the direction of negative infinity.
Nearest rounds the result of a calculation to the closest representable
number. In the case of a tie, Nearest rounds to the closest representable
number in the direction of positive infinity.
Round rounds the result of a calculation to the closest representable
number. In the case of a tie, Round rounds positive numbers to the closest
representable number in the direction of positive infinity, and rounds
negative numbers to the closest representable number in the direction
of negative infinity.
Simplest rounds the result of a calculation using the rounding mode
(Floor or Zero) that adds the least amount of extra rounding code to your
8-8
8-9
Fixed-Point Design
Arithmetic Operations
In this section...
Modulo Arithmetic on page 8-10
Twos Complement on page 8-11
Addition and Subtraction on page 8-12
Multiplication on page 8-13
Casts on page 8-16
Note These sections will help you understand what data type and scaling
choices result in overflows or a loss of precision.
Modulo Arithmetic
Binary math is based on modulo arithmetic. Modulo arithmetic uses only
a finite set of numbers, wrapping the results of any calculations that fall
outside the given set back into the set.
8-10
Arithmetic Operations
For example, the common everyday clock uses modulo 12 arithmetic. Numbers
in this system can only be 1 through 12. Therefore, in the clock system, 9
plus 9 equals 6. This can be more easily visualized as a number circle:
Similarly, binary math can only use the numbers 0 and 1, and any arithmetic
results that fall outside this range are wrapped around the circle to either 0
or 1.
Twos Complement
Twos complement is a way to interpret a binary number. In twos
complement, positive numbers always start with a 0 and negative numbers
always start with a 1. If the leading bit of a twos complement number is 0,
the value is obtained by calculating the standard binary value of the number.
If the leading bit of a twos complement number is 1, the value is obtained by
assuming that the leftmost bit is negative, and then calculating the binary
value of the number. For example,
8-11
Fixed-Point Design
01 (0 20 ) 1
11 ((21 ) (20 )) (2 1) 1
To compute the negative of a binary number using twos complement,
1 Take the ones complement, or flip the bits.
2 Add a 1 using binary math.
3 Discard any bits carried beyond the original word length.
For example, consider taking the negative of 11010 (-6). First, take the ones
complement of the number, or flip the bits:
11010 00101
Next, add a 1, wrapping all numbers to 0 or 1:
00101
1
00110 (6)
010010.1
(18.5)
0110.110 (6.75)
011001.010 (25.25)
Fixed-point subtraction is equivalent to adding while using the twos
complement value for any negative values. In subtraction, the addends
8-12
Arithmetic Operations
must be sign extended to match each others length. For example, consider
subtracting 0110.110 (6.75) from 010010.1 (18.5):
Most fixed-point DSP System Toolbox blocks that perform addition cast the
adder inputs to an accumulator data type before performing the addition.
Therefore, no further shifting is necessary during the addition to line up the
binary points. See Casts on page 8-16 for more information.
Multiplication
The multiplication of twos complement fixed-point numbers is directly
analogous to regular decimal multiplication, with the exception that the
intermediate results must be sign extended so that their left sides align
before you add them together.
For example, consider the multiplication of 10.11 (-1.25) with 011 (3):
8-13
Fixed-Point Design
8-14
Arithmetic Operations
8-15
Fixed-Point Design
System Toolbox blocks cast to the accumulator data type before performing
addition or subtraction operations. In the preceding diagram, this is
equivalent to the C code
acc=ac;
acc-=bd;
Casts
Many fixed-point System Toolbox blocks that perform arithmetic operations
allow you to specify the accumulator, intermediate product, and product
output data types, as applicable, as well as the output data type of the block.
This section gives an overview of the casts to these data types, so that you can
tell if the data types you select will invoke sign extension, padding with zeros,
rounding, and/or overflow.
8-16
Arithmetic Operations
Casting Examples
It is important to keep in mind the ramifications of each cast when selecting
these intermediate data types, as well as any other intermediate fixed-point
data types that are allowed by a particular block. Depending upon the data
types you select, overflow and/or rounding might occur. The following two
examples demonstrate cases where overflow and rounding can occur.
8-17
Fixed-Point Design
Cast from a Shorter Data Type to a Longer Data Type. Consider the
cast of a nonzero number, represented by a four-bit data type with two
fractional bits, to an eight-bit data type with seven fractional bits:
As the diagram shows, the source bits are shifted up so that the binary point
matches the destination binary point position. The highest source bit does
not fit, so overflow might occur and the result can saturate or wrap. The
empty bits at the low end of the destination data type are padded with either
0s or 1s:
If overflow does not occur, the empty bits are padded with 0s.
If wrapping occurs, the empty bits are padded with 0s.
If saturation occurs,
You can see that even with a cast from a shorter data type to a longer data
type, overflow might still occur. This can happen when the integer length of
the source data type (in this case two) is longer than the integer length of
8-18
Arithmetic Operations
the destination data type (in this case one). Similarly, rounding might be
necessary even when casting from a shorter data type to a longer data type, if
the destination data type and scaling has fewer fractional bits than the source.
Cast from a Longer Data Type to a Shorter Data Type. Consider the
cast of a nonzero number, represented by an eight-bit data type with seven
fractional bits, to a four-bit data type with two fractional bits:
As the diagram shows, the source bits are shifted down so that the binary
point matches the destination binary point position. There is no value for the
highest bit from the source, so the result is sign extended to fill the integer
portion of the destination data type. The bottom five bits of the source do not
fit into the fraction length of the destination. Therefore, precision can be
lost as the result is rounded.
In this case, even though the cast is from a longer data type to a shorter
data type, all the integer bits are maintained. Conversely, full precision can
be maintained even if you cast to a shorter data type, as long as the fraction
length of the destination data type is the same length or longer than the
8-19
Fixed-Point Design
fraction length of the source data type. In that case, however, bits are lost
from the high end of the result and overflow might occur.
The worst case occurs when both the integer length and the fraction length of
the destination data type are shorter than those of the source data type and
scaling. In that case, both overflow and a loss of precision can occur.
8-20
Description
Estimation
dsp.LevinsonSolver
Filters
dsp.AllpoleFilter
dsp.BiquadFilter
dsp.CICDecimator
dsp.CICInterpolator
8-21
Fixed-Point Design
(Continued)
Object
Description
dsp.DigitalFilter
dsp.FIRDecimator
dsp.FIRFilter
dsp.FIRInterpolator
dsp.FIRRateConverter
dsp.IIRFilter
dsp.LMSFilter
dsp.SubbandAnalysisFilter
8-22
dsp.ArrayVectorAdder
dsp.ArrayVectorDivider
dsp.ArrayVectorMultiplier
dsp.ArrayVectorSubtractor
dsp.CumulativeProduct
dsp.CumulativeSum
(Continued)
Object
Description
dsp.LDLFactor
dsp.LevinsonSolver
dsp.LowerTriangularSolver
dsp.LUFactor
dsp.Normalizer
Normalize input
dsp.UpperTriangularSolver
Quantizers
dsp.ScalarQuantizerDecoder Convert each index value into quantized
output value
dsp.ScalarQuantizerEncoder Perform scalar quantization encoding
dsp.VectorQuantizerDecoder Find vector quantizer codeword for given
index value
dsp.VectorQuantizerEncoder Perform vector quantization encoding
Signal Management
dsp.Buffer
dsp.Counter
Signal Operations
dsp.Convolver
dsp.DigitalDownConverter
dsp.DigitalUpConverter
8-23
Fixed-Point Design
(Continued)
Object
Description
dsp.NCO
dsp.PeakFinder
Window object
Sinks
dsp.SignalSink
dsp.TimeScope
Sources
dsp.SignalSource
dsp.SineWave
Statistics
8-24
dsp.Autocorrelator
dsp.Crosscorrelator
dsp.Histogram
dsp.Maximum
dsp.Mean
dsp.Median
dsp.Minimum
dsp.Variance
(Continued)
Object
Description
Transforms
dsp.DCT
dsp.FFT
dsp.IDCT
dsp.IFFT
8-25
Fixed-Point Design
8-26
specify the desired data type as fixed-point, the signedness, and the wordand fraction-lengths. System objects support these values of DataTypeMode:
Boolean, Double, Single, and Fixed-point: binary point scaling.
In the same way as for blocks, the data type properties of many System
objects can set the appropriate word lengths and scalings automatically by
using full precision. System objects assume that the target specified on the
Configuration Parameters Hardware Implementation target is ASIC/FPGA.
If you have not set the property that activates a dependent property and you
attempt to change that dependent property, a warning message displays. For
example, for the dsp.FFT object, before you set CustomOutputDataType to
numerictype(1,32,30) you must set OutputDataType to 'Custom'.
Note System objects do not support fixed-point word lengths greater than
128 bits.
For any System object provided in the Toolbox, the fimath settings for any
fimath attached to a fi input or a fi property are ignored. Outputs from a
System object never have an attached fimath.
8-27
Fixed-Point Design
8-28
All System Toolbox blocks with fixed-point capabilities share a set of common
parameters, but each block can have a different subset of these fixed-point
parameters. The following table provides an overview of the most common
fixed-point block parameters.
Fixed-Point Data
Type Parameter
Description
Rounding Mode
Overflow Mode
8-29
Fixed-Point Design
Fixed-Point Data
Type Parameter
Description
Product Output
Accumulator
Output
8-30
Logging
The Fixed-Point Tool logs overflows, saturations, and simulation minimums
and maximums for fixed-point System Toolbox blocks. The Fixed-Point Tool
does not log overflows and saturations when the Data overflow line in the
Diagnostics > Data Integrity pane of the Configuration Parameters dialog
box is set to None.
8-31
Fixed-Point Design
Autoscaling
You can use the Fixed-Point Tool autoscaling feature to set the scaling for
System Toolbox fixed-point data types.
8-32
8-33
Fixed-Point Design
8-34
8-35
Fixed-Point Design
8-36
ASIC/FPGA. Therefore, the accumulator data type used by the internal rule is
the ideal, full-precision result.
Calculate the full-precision word length for each of the Difference blocks in
the model:
8-37
Fixed-Point Design
As you can see in the dialog box, this device has 8-, 16-, and 32-bit word
lengths available. Therefore, the ideal word lengths of 10, 17, and 128 bits
calculated by the internal rule cannot be used. Instead, the internal rule uses
the next largest available word length in each case You can see this if you
rerun the model, as shown in the following figure.
8-38
8-39
Fixed-Point Design
8-40
8-41
Fixed-Point Design
As you can see in the dialog box, this device has 8-, 16-, and 32-bit word
lengths available. Therefore, the ideal word lengths of 12 and 31 bits
calculated by the internal rule cannot be used. Instead, the internal rule uses
the next largest available word length in each case. You can see this if you
rerun the model, as shown in the following figure.
8-42
8-43
Fixed-Point Design
This model uses the Cumulative Sum block to sum the input coming from the
Fixed-Point Sources subsystem. The Fixed-Point Sources subsystem outputs
two signals with different data types:
The Signed source has a word length of 16 bits and a fraction length of
15 bits.
The Unsigned source has a word length of 16 bits and a fraction length of
16 bits.
2 Run the model to check for overflow. MATLAB displays the following
8-44
open the Fixed-Point Tool by selecting Tools > Fixed-Point > Fixed-Point
Tool from the model menu. Turn on logging for all blocks in your model by
setting the Fixed-point instrumentation mode parameter to Minimums,
maximums and overflows.
4 Now that you have turned on logging, rerun the model by clicking the
Simulation button.
8-45
8-46
Fixed-Point Design
6 Assume a target hardware that supports 32-bit integers, and set the
b Double-click the block in the model, and select the Data Types pane
Assistant button (
8-47
Fixed-Point Design
d Set the Mode to Fixed Point. To see the representable range of the
current specified data type, click the Fixed-point details link. The tool
displays the representable maximum and representable minimum values
for the current data type.
e Change the Word length to 32, and click the Refresh details button in
8-48
When you change the value of the Word length parameter, the data type
string in the Data Type edit box automatically updates.
f Click OK on the block dialog box to save your changes and close the window.
g Set the word length of the Accumulator data type of the Unsigned
button.
3 Examine the results in the Contents pane of the Fixed-Point Tool. Because
you ran the model in Double override mode, you get an accurate, idealized
representation of the simulation minimums and maximums. These values
appear in the SimMin and SimMax parameters.
8-49
Fixed-Point Design
minimum and maximum values, you can more easily choose appropriate
fraction lengths. Before making these choices, save your active results to
reference so you can use them as your floating-point benchmark. To do so,
select Results > Move Active Results To Reference from the Fixed-Point
Tool menu. The status displayed in the Run column changes from Active to
Reference for all signals in your model.
check box. You did not specify any design minimums or maximums for the
data types in this model. Thus, the tool uses the logged information to compute
and propose fraction lengths. For information on specifying design minimums
and maximums, see Signal Ranges in the Simulink documentation.
3 Click the Propose fraction lengths button (
8-50
The proposed fraction length for the Accumulator data type of both the
Signed and Unsigned Cumulative Sum blocks is 17 bits.
To get more details about the proposed scaling for a particular data type,
highlight the data type in the Contents pane of the Fixed-Point Tool.
Open the Autoscale Information window for the highlighted data type
by clicking the Show autoscale information for the selected result
button (
).
2 When the Autoscale Information window opens, check the Value and
for each data type whose proposed scaling you want to keep. Then, click the
Apply accepted fraction lengths button (
). The tool updates the
specified data types on the block dialog boxes and the SpecifiedDT column in
the Contents pane.
4 To verify the newly accepted scaling, set the Data type override parameter
back to Use local settings, and run the model. Looking at Contents pane of
the Fixed-Point Tool, you can see the following details:
The SimMin and SimMax values of the Active run match the SimMin
and SimMax values from the floating-point Reference run.
There are no longer any overflows.
The SimDT does not match the SpecifiedDT for the Accumulator data
type of either Cumulative Sum block. This difference occurs because the
Cumulative Sum block always inherits its Signedness from the input
signal and only allows you to specify a Signedness of Auto. Therefore,
the SpecifiedDT for both Accumulator data types is fixdt([],32,17).
However, because the Signed Cumulative Sum block has a signed input
signal, the SimDT for the Accumulator parameter of that block is also
signed (fixdt(1,32,17)). Similarly, the SimDT for the Accumulator
parameter of the Unsigned Cumulative Sum block inherits its Signedness
from its input signal and thus is unsigned (fixdt(0,32,17)).
8-51
Fixed-Point Design
Quantizers
In this section...
Scalar Quantizers on page 8-52
Vector Quantizers on page 8-61
Scalar Quantizers
Analysis and Synthesis of Speech on page 8-52
Identify Your Residual Signal and Reflection Coefficients on page 8-54
Create a Scalar Quantizer on page 8-56
model.
8-52
Quantizers
8-53
Fixed-Point Design
command line.
2 Save the model file as ex_sq_example2 in your working folder.
3 From the Sinks library, click-and-drag two Signal To Workspace blocks
Workspace blocks.
5 Double-click this Signal To Workspace block and set the Variable name
8-54
Quantizers
7 Double-click this Signal To Workspace block and set the Variable name
The residual signal, E, and your reflection coefficients, K, are defined in the
MATLAB workspace. In the next topic, you use these variables to design
your scalar quantizers.
8-55
Fixed-Point Design
Coefficients on page 8-54 is not open on your desktop, you can open an
equivalent model by typing ex_sq_example2 at the MATLAB command
prompt.
2 Run this model to define the variables E and K in the MATLAB workspace.
3 From the Quantizers library, click-and-drag a Scalar Quantizer Design
block into your model. Double-click this block to open the SQ Design Tool
GUI.
4 For the Training Set parameter, enter K.
Reflection Coefficients.
8 For the Decoder block name parameter, enter SQ Decoder -
Reflection Coefficients.
8-56
Quantizers
current model. You can type gcs in the MATLAB Command Window to
display the name of your current model.
8-57
Fixed-Point Design
10 In the SQ Design Tool GUI, click the Design and Plot button to apply the
8-58
Quantizers
Two new blocks, SQ Encoder - Reflection Coefficients and SQ Decoder Reflection Coefficients, appear in your model file.
12 Click the SQ Design Tool GUI and, for the Training Set parameter, enter
E.
13 Repeat steps 5 to 11 for the variable E, which represents the residual signal
you want to quantize. In steps 6 and 7, name your blocks SQ Encoder Residual and SQ Decoder - Residual.
Once you have completed these steps, two new blocks, SQ Encoder Residual and SQ Decoder - Residual, appear in your model file.
14 Close the SQ Design Tool GUI. You do not need to save the SQ Design
Tool session.
You have now created a scalar quantizer encoder and a scalar quantizer
decoder for each signal you want to quantize. You are ready to quantize the
residual signal, E, and the reflection coefficients, K.
8-59
Fixed-Point Design
to both signals.
Again, there is no perceptible difference between the two. You can therefore
conclude that quantizing your residual and reflection coefficients did not
affect the ability of your system to accurately reproduce the input signal.
You have now quantized the residual and reflection coefficients. The bit rate
of a quantization system is calculated as (bits per frame)*(frame rate).
In this example, the bit rate is [(80 residual samples/frame)*(7 bits/sample) +
(12 reflection coefficient samples/frame)*(7 bits/sample)]*(100 frames/second),
or 64.4 kbits per second. This is higher than most modern speech coders,
8-60
Quantizers
which typically have a bit rate of 8 to 24 kbits per second. If you decrease the
number of bits allocated for the quantization of the reflection coefficients or
the residual signal, the overall bit rate would decrease. However, the speech
quality would also degrade.
For information about decreasing the bit rate without affecting speech quality,
see Vector Quantizers on page 8-61.
Vector Quantizers
Build Your Vector Quantizer Model on page 8-61
Configure and Run Your Model on page 8-63
8-61
Fixed-Point Design
your model.
4 From the DSP System Toolbox Estimation > Linear Prediction library,
8-62
Quantizers
8-61 is not open on your desktop, you can open an equivalent model by
typing ex_vq_example2 at the MATLAB command prompt.
2 Double-click the LSF Vector Quantization subsystem, and then double-click
8-63
Fixed-Point Design
The subsystem opens, and you see the three Vector Quantizer Encoder
blocks used to implement the split vector quantization method.
8-64
Quantizers
8-65
Fixed-Point Design
8-66
Quantizers
8-67
Fixed-Point Design
8-68
8-69
Fixed-Point Design
Process Overview
The conversion from floating point to fixed point consists of two main parts:
quantizing the coefficients and performing the dynamic range analysis.
Quantizing the coefficients is a process of converting the coefficients to
fixed-point numbers. The dynamic range analysis is a process of fine tuning
the scaling of each node to ensure that the fraction lengths are set for full
input range coverage and maximum precision. The following steps describe
this conversion process.
8-70
where the passband is from .45 to .55 of normalized frequency, the amount
of ripple acceptable in the passband is 1 dB, the first stopband is from 0 to
.35 (normalized), the second stopband is from .65 to 1 (normalized), and both
stopbands provide 60 dB of attenuation.
To design this filter, evaluate the following code, or type it at the MATLAB
command prompt:
f = fdesign.bandpass(.35,.45,.55,.65,60,1,60);
Hd = design(f, 'equiripple');
fvtool(Hd)
8-71
Fixed-Point Design
The last line of code invokes the Filter Visualization Tool, which displays the
designed filter. You use Hd, which is a double, floating-point filter, both as the
baseline and a starting point for the conversion.
8-72
As the figure shows, the filter design constraints are not met. The attenuation
is not complete, and there is noise at the edges of the stopbands. You can
experiment with different coefficient word lengths if you like. For this
example, however, the word length of 12 is sufficient.
To set the coefficient word length of 12, evaluate or type the following code
at the MATLAB command prompt:
set(Hf, 'CoeffWordLength', 12);
fvtool(Hf)
The resulting filter satisfies the design constraints, as shown in the following
figure.
8-73
Fixed-Point Design
Now that the coefficient word length is set, there are other data width
constraints that might require attention. Type the following at the MATLAB
command prompt:
>> info(Hf)
Discrete-Time FIR Filter (real)
------------------------------Filter Structure : Direct-Form FIR
Filter Length
: 48
Stable
: Yes
Linear Phase
: Yes (Type 2)
Arithmetic
: fixed
8-74
Numerator
: s12,14 -> [-1.250000e-001 1.250000e-001)
Input
: s16,15 -> [-1 1)
Filter Internals : Full Precision
Output
: s31,29 -> [-2 2) (auto determined)
Product
: s27,29 -> [-1.250000e-001 1.250000e-001)...
(auto determined)
Accumulator
: s31,29 -> [-2 2) (auto determined)
Round Mode
: No rounding
Overflow Mode
: No overflow
You see the output is 31 bits, the accumulator requires 31 bits and the
multiplier requires 27 bits. A typical piece of hardware might have a 16 bit
data bus, a 24 bit multiplier, and an accumulator with 4 guard bits. Another
reasonable assumption is that the data comes from a 12 bit ADC. To reflect
these constraints type or evaluate the following code:
set
set
set
set
set
(Hf,
(Hf,
(Hf,
(Hf,
(Hf,
'InputWordLength', 12);
'FilterInternals', 'SpecifyPrecision');
'ProductWordLength', 24);
'AccumWordLength', 28);
'OutputWordLength', 16);
Although the filter is basically done, if you try to filter some data with it at
this stage, you may get erroneous results due to overflows. Such overflows
occur because you have defined the constraints, but you have not tuned the
filter coefficients to handle properly the range of input data where the filter
is designed to operate. Next, the dynamic range analysis is necessary to
ensure no overflows.
8-75
Fixed-Point Design
ever occurs. This worst-case input signal is a scaled version of the sign of
the flipped impulse response.
To scale the coefficients based on the full dynamic range, type or evaluate
the following code:
x = 1.9*sign(fliplr(impz(Hf)));
Hf = autoscale(Hf, x);
To check that the coefficients are in range (no overflows) and have maximum
possible precision, type or evaluate the following code:
fipref('LoggingMode', 'on', 'DataTypeOverride', 'ForceOff');
y = filter(Hf, x);
fipref('LoggingMode', 'off');
R = qreport(Hf)
8-76
The report shows no overflows, and all data falls within the designed range.
The conversion has completed successfully.
When fvtool displays the filter using the Magnitude response view, the
quantized filter seems to match the original filter quite well.
8-77
Fixed-Point Design
However if you look at the Magnitude Response Estimate plot from the
Analysis menu, you will see that the actual filter created may not perform
nearly as well as indicated by the Magnitude Response plot.
8-78
8-79
Fixed-Point Design
The register has a WordLength of B, or in other words it has B bits. The bits
are numbered from left to right from 0 to B-1. The most significant bit (MSB)
is the leftmost bit, bB-1. The least significant bit is the right-most bit, b0. You
can think of the FracLength as a quantity specifying how to interpret the bits
stored and resolve the value they represent. The value represented by the bits
is determined by assigning a weight to each bit:
8-80
value = bB1 2 B1 L +
B2
bk 2k L
k =0
.
The value 2L is the smallest possible difference between two numbers
represented in this format, otherwise known as the quantization step. In
this way, it is preferable to think of the FracLength as the negative of
the exponent used to weigh the right-most, or least-significant, bit of the
fixed-point number.
To reduce the number of bits used to represent a given quantity, you can
discard the least-significant bits. This method minimizes the quantization
error since the bits you are removing carry the least weight. For instance, the
following figure illustrates reducing the number of bits from 4 to 2:
2(8) = 28 = 256 . So you will still have the same range of values, but
with less precision, and the numbers that can be represented become
{32768, 32512,..., 256, 0, 256,...32256, 32512} .
8-81
Fixed-Point Design
With this quantization the largest possible error becomes about 256/2 when
rounding to the nearest, with a special case for 32767.
bsc = b*2^L;
Alternatively, you can use the fixed-point numbers autoscaling tool as follows:
bq = fi(b, true, B); % signed = true, B = 18 bits
L = bq.FractionLength;
It is a coincidence that B and L are both 18 in this case, because of the value
of the largest coefficient of b. If, for example, the maximum value of b were
0.124, L would be 20 while B (the number of bits) would remain 18.
Build the FIR Filter. First create the filter using the direct form, tapped
delay line structure:
8-82
h = dfilt.dffir(bsc);
Now you can examine the magnitude response of the filter using fvtool:
fvtool(h, 'Color', 'white')
8-83
Fixed-Point Design
This shows a large gain of 117 dB in the passband, which is due to the large
values of the coefficients this will cause the output of the filter to be much
larger than the input. A method of addressing this will be discussed in the
following sections.
Set the Filter Parameters to Work with Integers. You will need to set
the input parameters of your filter to appropriate values for working with
integers. For example, if the input to the filter is from a A/D converter with
12 bit resolution, you should set the input as follows:
h.InputWordLength = 12;
h.InputFracLength = 0;
8-84
: Direct-Form FIR
Filter Length
: 101
Stable
: Yes
Linear Phase
: Yes (Type 1)
Arithmetic
: fixed
Numerator
Input
Filter Internals
: Full Precision
Output
Product
Accumulator
Round Mode
: No rounding
Overflow Mode
: No overflow
(auto determined)
(auto determined)
(auto determined)
In this case, all the fractional lengths are now set to zero, meaning that the
filter h is set up to handle integers.
Create a Test Signal for the Filter. You can generate an input signal for the
filter by quantizing to 12 bits using the autoscaling feature, or you can follow
the same procedure that was used for the coefficients, discussed previously.
In this example, create a signal with two sinusoids:
n = 0:999;
f1 = 0.1*pi; % Normalized frequency of first sinusoid
f2 = 0.8*pi; % Normalized frequency of second sinusoid
x = 0.9*sin(0.1*pi*n) + 0.9*sin(0.8*pi*n);
xq = fi(x, true, 12); % signed = true, B = 12
xsc = fi(xq.int, true, 12, 0);
Filter the Test Signal. To filter the input signal generated above, enter
the following:
ysc = filter(h, xsc);
8-85
Fixed-Point Design
Here ysc is a full precision output, meaning that no bits have been discarded
in the computation. This makes ysc the best possible output you can achieve
given the 12bit input and the 18bit coefficients. This can be verified by
filtering using double-precision floating-point and comparing the results of
the two filtering operations:
hd = double(h);
xd = double(xsc);
yd = filter(hd, xd);
norm(yd-double(ysc))
ans =
0
Now you can examine the output compared to the input. This example is
plotting only the last few samples to minimize the effect of transients:
idx = 800:950;
xscext = double(xsc(idx)');
gd = grpdelay(h, [f1 f2]);
yidx = idx + gd(1);
yscext = double(ysc(yidx)');
stem(n(idx)', [xscext, yscext]);
axis([800 950 -2.5e8 2.5e8]);
legend('input', 'output');
set(gcf, 'color', 'white');
8-86
It is difficult to compare the two signals in this figure because of the large
difference in scales. This is due to the large gain of the filter, so you will
need to compensate for the filter gain:
stem(n(idx)', [2^18*xscext, yscext]);
axis([800 950 -5e8 5e8]);
legend('scaled input', 'output');
8-87
Fixed-Point Design
You can see how the signals compare much more easily once the scaling has
been done, as seen in the above figure.
Truncate the Output WordLength. If you examine the output wordlength,
ysc.WordLength
ans =
31
you will notice that the number of bits in the output is considerably greater
than in the input. Because such growth in the number of bits representing
the data may not be desirable, you may need to truncate the wordlength of
the output. As discussed in Terminology of Fixed-Point Numbers on page
8-80the best way to do this is to discard the least significant bits, in order
to minimize error. However, if you know there are unused high order bits,
you should discard those bits as well.
8-88
To determine if there are unused most significant bits (MSBs), you can look at
where the growth in WordLength arises in the computation. In this case, the
bit growth occurs to accommodate the results of adding products of the input
(12 bits) and the coefficients (18 bits). Each of these products is 29 bits long
(you can verify this using info(h)). The bit growth due to the accumulation of
the product depends on the filter length and the coefficient values- however,
this is a worst-case determination in the sense that no assumption on the
input signal is made besides, and as a result there may be unused MSBs. You
will have to be careful though, as MSBs that are deemed unused incorrectly
will cause overflows.
Suppose you want to keep 16 bits for the output. In this case, there is no
bit-growth due to the additions, so the output bit setting will be 16 for the
wordlength and 14 for the fraction length.
Since the filtering has already been done, you can discard some bits from ysc:
yout = fi(ysc, true, 16, -14);
Alternatively, you can set the filter output bit lengths directly (this is useful if
you plan on filtering many signals):
specifyall(h);
h.OutputWordLength = 16;
h.OutputFracLength = -14;
yout2 = filter(h, xsc);
You can verify that the results are the same either way:
norm(double(yout) - double(yout2))
ans =
0
However, if you compare this to the full precision output, you will notice that
there is rounding error due to the discarded bits:
norm(double(yout)-double(ysc))
8-89
Fixed-Point Design
ans =
1.446323386867543e+005
In this case the differences are hard to spot when plotting the data, as seen
below:
stem(n(yidx), [double(yout(yidx)'), double(ysc(yidx)')]);
axis([850 950 -2.5e8 2.5e8]);
legend('Scaled Input', 'Output');
set(gcf, 'color', 'white');
8-90
Scale the Output. Because the filter in this example has such a large
gain, the output is at a different scale than the input. This scaling is purely
theoretical however, and you can scale the data however you like. In this
case, you have 16 bits for the output, but you can attach whatever scaling you
choose. It would be natural to reinterpret the output to have a weight of 2^0
(or L = 0) for the LSB. This is equivalent to scaling the output signal down
by a factor of 2^(-14). However, there is no computation or rounding error
involved. You can do this by executing the following:
yri = fi(yout.int, true, 16, 0);
stem(n(idx)', [xscext, double(yri(yidx)')]);
axis([800 950 -1.5e4 1.5e4]);
legend('input', 'rescaled output');
This plot shows that the output is still larger than the input. If you had done
the filtering in double-precision floating-point, this would not be the case
because here more bits are being used for the output than for the input, so the
8-91
Fixed-Point Design
MSBs are weighted differently. You can see this another way by looking at
the magnitude response of the scaled filter:
[H,w] = freqz(h);
plot(w/pi, 20*log10(2^(-14)*abs(H)));
This plot shows that the passband gain is still above 0 dB.
To put the input and output on the same scale, the MSBs must be weighted
equally. The input MSB has a weight of 2^11, whereas the scaled output
MSB has a weight of 2^(2914) = 2^15. You need to give the output MSB
a weight of 2^11 as follows:
yf = fi(zeros(size(yri)), true, 16, 4);
yf.bin = yri.bin;
stem(n(idx)', [xscext, double(yf(yidx)')]);
legend('input', 'rescaled output');
8-92
8-93
Fixed-Point Design
8-94
The coefficients are represented with 18 bits and the input signal is
represented with 12 bits:
g = set2int(h, 18, 12);
g_dB = 20*log10(g)
g_dB =
1.083707984390332e+002
The set2int method returns the gain of the filter by scaling the coefficients
to integers, so the gain is always a power of 2. You can verify that the gain we
get here is consistent with the gain of the filter previously. Now you can also
check that the filter h is set up properly to work with integers:
info(h)
Discrete-Time FIR Filter (real)
------------------------------Filter Structure
: Direct-Form FIR
Filter Length
: 101
Stable
: Yes
Linear Phase
: Yes (Type 1)
Arithmetic
: fixed
Numerator
8-95
Fixed-Point Design
Input
Filter Internals
: Full Precision
Output
Product
: No rounding
Overflow Mode
: No overflow
Here you can see that all fractional lengths are now set to zero, so this filter is
set up properly for working with integers.
Reinterpret the Output. You can compare the output to the double-precision
floating-point reference output, and verify that the computation done by the
filter h is done in full precision.
yint = filter(h, xsc);
norm(yd - double(yint))
ans =
0
8-96
Once again, the plot shows that the input and output are at different scales.
In order to scale the output so that the signals can be compared more easily
in a plot, you will need to weigh the MSBs appropriately. You can compute
the new fraction length using the gain of the filter when the coefficients were
integer numbers:
WL = yout.WordLength;
FL = yout.FractionLength + log2(g);
yf2 = fi(zeros(size(yout)), true, WL, FL);
yf2.bin = yout.bin;
stem(n(idx)', [xscext, double(yf2(yidx)')]);
axis([800 950 -2e3 2e3]);
legend('input', 'rescaled output');
8-97
Fixed-Point Design
This final plot shows the filtered data re-scaled to match the input scale.
8-98
Digital Filter
Filter Realization Wizard
FIR Decimation
FIR Interpolation
Two-Channel Analysis Subband Filter
Two-Channel Synthesis Subband Filter
8-99
Fixed-Point Design
8-100
9
Code Generation
Learn how to generate code for signal processing applications.
Understanding Code Generation on page 9-2
Functions and System Objects Supported for Code Generation on page 9-4
Generate Code from MATLAB on page 9-12
Generate Code from Simulink on page 9-13
How to Run a Generated Executable Outside MATLAB on page 9-18
Verify FIR Filter on ARM Cortex-M Processor on page 9-19
CMSIS Conditions for DSP System objects to Support ARM Cortex-M
on page 9-24
Fixed-Point Property Settings for dsp.FIRFilter on page 9-31
Fixed-Point Property Settings for Discrete FIR Filter block on page 9-32
CMSIS Conditions for DSP Blocks to Support ARM Cortex-M on page 9-33
Support Packages and Support Package Installer on page 9-41
Open Examples for This Support Package on page 9-43
Install This Support Package on Other Computers on page 9-47
Supported CMSIS Functions for ARM Cortex-M Processors on page
9-49
Code Generation
Simulink Coder provides functions to help you set up and manage the build
information for your models. For example, one of the functions that Simulink
Coder provides is getNonBuildFiles. This function allows you to identify the
shared libraries required by blocks in your model. If your model contains any
blocks that use precompiled shared libraries, you can install those libraries
9-2
on the target system. The folder that you install the shared libraries in must
be on the system path. The target system does not need to have MATLAB
installed, but it does need to be supported by MATLAB.
9-3
Code Generation
Estimation
9-4
dsp.BurgAREstimator
dsp.BurgSpectrumEstimator
dsp.CepstralToLPC
dsp.CrossSpectrumEstimator
dsp.LevinsonSolver
dsp.LPCToAutocorrelation
dsp.LPCToCepstral
dsp.LPCToLSF
dsp.LPCToLSP
dsp.LPCToRC
dsp.LSFToLPC
dsp.LSPToLPC
dsp.RCToAutocorrelation
dsp.RCToLPC
dsp.SpectrumEstimator
Name
dsp.TransferFunctionEstimator
Filters
ca2tf
cl2tf
dsp.AdaptiveLatticeFilter
dsp.AffineProjectionFilter
dsp.AllpoleFilter
dsp.CICDecimator
dsp.CICInterpolator
dsp.DigitalFilter
dsp.FilteredXLMSFilter
dsp.FIRDecimator
9-5
Code Generation
Name
dsp.FIRFilter
dsp.FIRRateConverter
dsp.FrequencyDomainAdaptiveFilter
dsp.IIRFilter
dsp.LMSFilter
dsp.RLSFilter
firceqrip
fireqint
firgr
9-6
Name
firlpnorm
firnyquist
firpr2chfb
ifir
iircomb
iirgrpdelay
9-7
Code Generation
Name
iirlpnorm
iirpeak
tf2ca
tf2cl
Math Operations
9-8
dsp.ArrayVectorAdder
dsp.ArrayVectorDivider
dsp.ArrayVectorMultiplier
dsp.ArrayVectorSubtractor
dsp.CumulativeProduct
dsp.CumulativeSum
Name
dsp.LDLFactor
dsp.LevinsonSolver
dsp.LowerTriangularSolver
dsp.LUFactor
dsp.Normalizer
dsp.UpperTriangularSolver
Quantizers
dsp.ScalarQuantizerDecoder
dsp.ScalarQuantizerEncoder
dsp.VectorQuantizerDecoder
dsp.VectorQuantizerEncoder
Scopes
dsp.SpectrumAnalyzer
dsp.TimeScope
Signal Management
dsp.Counter
dsp.DelayLine
Signal Operations
dsp.Convolver
dsp.DCBlocker
dsp.Delay
dsp.DigitalDownConverter
dsp.DigitalUpConverter
9-9
Code Generation
Name
dsp.Interpolator
dsp.NCO
dsp.PeakFinder
dsp.PhaseUnwrapper
dsp.VariableFractionalDelay
dsp.VariableIntegerDelay
dsp.Window
Sinks
dsp.AudioPlayer
dsp.AudioFileWriter
dsp.UDPSender
Sources
dsp.AudioFileReader
dsp.AudioRecorder
dsp.SignalSource
dsp.SineWave
Statistics
9-10
Name
dsp.Autocorrelator
dsp.Crosscorrelator
dsp.Histogram
dsp.Mean
dsp.Median
dsp.Minimum
dsp.RMS
dsp.StandardDeviation
dsp.Variance
Transforms
dsp.AnalyticSignal
dsp.DCT
dsp.FFT
dsp.IDCT
dsp.IFFT
9-11
Code Generation
9-12
Note You must have both the DSP System Toolbox and Simulink Coder
products installed on your computer to complete the procedures in this section.
9-13
Code Generation
Run the model and observe the output in both scopes. This model saves the
filter weights each time they adapt. You can plot the last set of coefficients
using the following command:
plot(filter_wts(:,:,1201))
9-14
setup
Code Generation tab, and clear the Generate Code Only checkbox.
2 Click OK to apply your changes and close the dialog box.
9-15
Code Generation
).
Because you re-configured the model to generate and build code, the code
generation process continues until the code is compiled and linked.
Running the generated code creates a MAT-file which contains the same
variables as those generated by simulating the model. The variables in the
MAT-file are named with a prefix of rt_. After you run the generated code,
you can load the variables from the MAT-file by typing the following command
at the MATLAB prompt:
load ex_codegen_dsp.mat
You can now compare the variables from the generated code with the
variables from the model simulation. To plot the last set of coefficients from
the generated code, enter the following command at the MATLAB prompt:
plot(rt_filter_wts(:,:,1201))
The last set of coefficients from the generated code are shown in the following
figure.
9-16
For further information on generating code from Simulink, see the Simulink
Coder documentation.
9-17
Code Generation
9-18
Platform
Command
Mac
setenv DYLD_LIBRARY_PATH
$DYLD_LIBRARY_PATH:
$MATLABROOT/bin/maci64
(csh/tcsh)export
DYLD_LIBRARY_PATH
$DYLD_LIBRARY_PATH:
$MATLABROOT/bin/maci64 (Bash)
Linux
setenv LD_LIBRARY_PATH
$LD_LIBRARY_PATH:
$MATLABROOT/bin/glnxa64
(csh/tcsh)export
LD_LIBRARY_PATH
$LD_LIBRARY_PATH:
$MATLABROOT/bin/glnxa64 (Bash)
Windows
set PATH =
$MATLABROOT\bin\win32;%PATH%
set PATH =
$MATLABROOT\bin\win64;%PATH%
9-19
Code Generation
9-20
choose C/C++ Code > Build This Subsystem. When the Build code for
Subsystem dialog box opens, Click Build to start generating code.
9-21
Code Generation
9-22
9-23
Code Generation
9-24
The following table illustrates the rules under which CMSIS supports these
System objects offering ARM support:
DSP System object
System object
properties for CMSIS
Support
Equivalent CMSIS
Methods
dsp.FIRFilter
Structure: Direct
'Direct Form'
Structure,
Form or Lattice
MA
InitialConditions:
0
arm_fir_f32
arm_fir_init_f32
fixed-point input
FrameBasedProcessing:
with q7 format:
true
Input: real, and
single channel (one
column)
arm_fir_q7
For 'Direct
Form' Structure:
NumeratorSource:
Property or Input
fixed-point input
with q15 format:
arm_fir_init_q7
arm_fir_q15
port
arm_fir_init_q15
For 'Lattice
fixed-point input
MA' Structure:
with q31 format:
ReflectionCoefficientSource:
Property or Input
arm_fir_q31
port
The following
settings are needed
to support fixed-point
FIR filter with
Direct Form
Structure:
arm_fir_init_q31
'Lattice MA'
Structure,
arm_fir_lattice_f32
9-25
Code Generation
System object
properties for CMSIS
Support
Equivalent CMSIS
Methods
arm_fir_lattice_init_f32
FullPrecisionOverride:
false
RoundingMethod:
'Floor'
OverflowAction:
'Saturate'
Fixed-Point
Property Settings
for dsp.FIRFilter on
page 9-31
Q15 specific:
Number of filter
coefficients must be
even and greater
than or equal to 4. If
not, pad zeros at the
end.
dsp.FIRDecimator
Structure: Direct
Form
arm_fir_decimate_init_f32
arm_fir_decimate_f32
9-26
arm_fir_interpolate_init_f32
arm_fir_interpolate_f32
System object
properties for CMSIS
Support
Equivalent CMSIS
Methods
dsp.LMSFilter
StepSizeSource:
arm_lms_init_f32
'Property'
arm_lms_f32
WeightResetInputPort:
If the algorithm is
false
Normalized LMS:
WeightsOutputPort:
false
arm_lms_norm_f32
arm_lms_norm_init_f32
AdaptInputPort:
false
LeakageFactor:
1.0
InitialConditions:
0
Method: LMS or
Normalized LMS
dsp.BiquadFilter
SOSMatrixSource
: 'Property' or
'Input port'
arm_biquad_cascade_df1_init_f32
arm_biquad_cascade_df2T_init_f3
arm_biquad_cascade_df1_f32
No replacement for
DFILT object
arm_biquad_cascade_df2T_f32
Structure:
Direct Form I or
Direct Form II
transposed
InitialConditions:
0
9-27
Code Generation
System object
properties for CMSIS
Support
Equivalent CMSIS
Methods
FrameBasedProcessing
: True
ScaleValuesInputPort
: False(when the
SOSMatrixSource
is set to 'Input
Port')
dsp.FFT
FFTImplementation: arm_cfft_radix2_init_f32
Radix-2
arm_cfft_radix2_f32
Normalize : False
FFTLength:
16,
FFTLengthSource
: 'Property'
WrapInput : does
not matter because
input length must
equal FFT length
Input: complex
single
9-28
Restriction: Input
length must
equal FFT length,
because of CMSIS
in-place FFT
algorithm
System object
properties for CMSIS
Support
dsp.IFFT
FFTImplementation: arm_cfft_radix2_init_f32
Radix-2
Equivalent CMSIS
Methods
arm_cfft_radix2_f32
Normalize : true
FFTLengthSource
: 'Property'
FFTLength:
16,
ConjugateSymmetricInput
: false
WrapInput : does
not matter because
input length must
equal FFT length
Input: complex
single
Restriction: Input
length must
equal FFT length,
because of CMSIS
in-place FFT
algorithm
9-29
Code Generation
System object
properties for CMSIS
Support
Equivalent CMSIS
Methods
dsp.CrossCorrelator
dsp.Convolver
Method : Time
arm_conv_f32
Domain
Input : Single
channel
The two inputs must
be of the same length
arm_correlate_f32
There are no
init methods
associated with these
algorithms.
Non-running
mode only (e.g.,
RunningMean :
false)
ROIProcessing:
false (does not
apply to RMS)
Dimension : All
(find statistic over
entire input
Input is
one-dimensional
Input : single
channel, not scalar,
real
9-30
arm_mean_f32
arm_rms_f32
arm_var_f32
arm_std_f32
There are no
init methods
associated with these
algorithms.
Q7
CoefficientDataType
Custom
Q15
Q31
Custom
Custom
CustomCoefficientsDataType
numerictype(true,8,7)
numerictype(true,16,15)
numerictype(true,32,31)
ProductDataType Custom
Custom
Custom
CustomProductDataType
numerictype(true,16,14)
numerictype(true,32,30)
numerictype(true,64,62)
AccumulatorDataType
Custom
Custom
Custom
CustomAccumulatorDataType
numerictype(true,32,14)
numerictype(true,64,30)
numerictype(true,64,62)
OutputDataType
Same as input or
Custom
Same as input or
Custom
Same as input or
Custom
CustomOutputDataType
numerictype(true,8,7)
numerictype(true,16,15)
numerictype(true,32,31)
[Note]
9-31
Code Generation
q31
CoefDataTypeStr fixdt(true,8,7)
fixdt(true,16,15)
fixdt(true,32,31)
ProductDataTypeStr
fixdt(true,16,14)
fixdt(true,32,30)
fixdt(true,64,62)
AccumDataTypeStrfxdt(true,32,14)
fxdt(true,64,30)
fxdt(true,64,62)
OutputDataType
Inherit: Same
as input or
fxpt(true,16,15)
Inherit: Same
as input or
fxdt(true, 32,31)
Fixed-Point
Property Name
9-32
q7
Inherit: Same
as input or
fxdt(true,8,7)
9-33
Code Generation
The following table illustrates the rules under which CMSIS supports these
blocks offering ARM support:
DSP Block
Equivalent CMSIS
Methods
Filter structure:
'Direct Form'
Structure:
Direct Form or
Lattice MA
Input is real
Input processing:
Columns as channels
(frame based); and
input has one column
Input : single
channel
Initial states : 0
Coefficients
source: Dialog
parameters or Input
port
The following
settings are needed
to support fixed-point
Discrete FIR Filter
block, in Direct
Form Structure
only:
RndMeth:
'Floor'
arm_fir_f32
arm_fir_init_f32
fixed-point input
with q7 format:
arm_fir_q7
arm_fir_init_q7
fixed-point input
with q15 format:
arm_fir_q15
arm_fir_init_q15
fixed-point input
with q31 format:
arm_fir_q31
arm_fir_init_q31
'Lattice MA'
Structure:
arm_fir_lattice_f32
SaturateOnIntegerOverflow:
on
9-34
DSP Block
Equivalent CMSIS
Methods
lockScale: on
arm_fir_lattice_init_f32
Fixed-Point
Property Settings
for Discrete FIR
Filter block on page
9-32
Q15 Specific:
Number of filter
coefficients must be
even and greater
than or equal to 4. If
not, pad zeros at the
end.
FIR Decimation
Filter structure:
Direct Form
arm_fir_decimate_init_f32
arm_fir_decimate_f32
Input processing:
Columns as
channels
(frame-based), and
Coefficients
source: Dialog
parameters
9-35
Code Generation
DSP Block
Equivalent CMSIS
Methods
FIR Interpolation
Input processing
: Columns as
arm_fir_interpolate_init_f32
channels (frame
based), and input
arm_fir_interpolate_f32
Coefficients
source: Dialog
parameters
LMS Filter
9-36
arm_lms_init_f32
arm_lms_f32
If the algorithm is
Normalized LMS:
arm_lms_norm_f32
arm_lms_norm_init_f32
DSP Block
Equivalent CMSIS
Methods
Algorithm is either
LMS or Normalized
LMS
Biquad Filter
Coefficients
source: Dialog
parameters or Input
arm_biquad_cascade_df1_init_f32
arm_biquad_cascade_df2T_init_f3
port(s)
arm_biquad_cascade_df1_f32
arm_biquad_cascade_df2T_f32
Restriction: If
Coefficient
source is
Input port(s),
replacement only
occurs when Scale
value mode is set
to Assume all
are unity and
optimize
No replacement for
DFILT object
Filter structure:
Direct Form I or
Direct Form II
transposed
Initial conditions:
0
Input processing:
Columns as
channels (frame
based)
9-37
Code Generation
DSP Block
Equivalent CMSIS
Methods
FFT
FFT
implementation:
arm_cfft_radix2_init_f32
Radix-2
Scale result
by FFT length:
uncheck (or OFF)
Inherit FFT
length from
input dimensions:
uncheck (or OFF)
Restriction: Input
Length must be
equal to FFT
Length because
of CMSIS FFT
algorithm
FFT length:
16,
Input: complex
single
9-38
Restriction: Input
length must
equal FFT length,
because of CMSIS
in-place FFT
algorithm
arm_cfft_radix2_f32
DSP Block
Equivalent CMSIS
Methods
IFFT
FFT
implementation:
arm_cfft_radix2_init_f32
Radix-2
arm_cfft_radix2_f32
Divide output by
FFT length: check
(or ON)
Inherit FFT
length from
input dimensions:
uncheck (or OFF)
Restriction: Input
Length must be
equal to FFT
Length because
of CMSIS FFT
algorithm
FFT length:
16,
Output sampling
mode: both sample
based and frame
based
Input: complex
single
Restriction: Input
length must
equal FFT length,
because of CMSIS
in-place FFT
algorithm
9-39
Code Generation
DSP Block
Equivalent CMSIS
Methods
Correlation
Convolution
Computation
domain: Time
arm_conv_f32
Input: Single
channel
The two inputs must
be of the same length
arm_correlate_f32
There are no
init methods
associated with these
algorithms.
Non-running mode
only
arm_mean_f32
ROI Processing:
disabled (does not
apply to RMS)
arm_var_f32
Input is
one-dimensional
Input: single
channel, not scalar,
real
9-40
arm_rms_f32
arm_std_f32
There are no
init methods
associated with these
algorithms.
9-41
Code Generation
9-42
(F1).
9-43
Code Generation
9-44
Note For other types of examples, open the Help browser and search for your
product name followed by examples.
9-45
9-46
Code Generation
example, you can share the folder on the network, or copy the folder to
portable media, such as a USB flash drive.
9-47
Code Generation
option.
3 Click Browse to specify the location of the support package folder on the
9-48
DSP Operations
Filter
CMSIS Function
arm_fir_f32
FIR Decimation
arm_fir_decimate
FIR Interpolation
arm_fir_interpolate
Convolution
arm_conv
Correlation
arm_fir_f32
Biquad Filter
arm_biquad_cascade_df1
LMS Filter
arm_lms
FFT
arm_cfft_radix2_f32
IFFT
arm_cfft_radix2_f32
RMS
arm_rms
Standard Deviation
arm_std
Variance
arm_var
Math Operations
Operation
CMSIS function
Note
arm_abs_f32
arm_abs_q31
9-49
Code Generation
9-50
Operation
CMSIS function
Note
arm_abs_q15
arm_abs_q7
Vector Addition
arm_add_f32
Vector Addition
arm_add_q31
Vector Addition
arm_add_q15
Vector Addition
arm_add_q7
Vector Subtraction
arm_sub_f32
Vector Subtraction
arm_sub_q31
Vector Subtraction
arm_sub_q15
Vector Subtraction
arm_sub_q7
Vector Multiplication
arm_mult_f32
Vector Multiplication
arm_mult_q31
Vector Multiplication
arm_mult_q15
Vector Multiplication
arm_mult_q7
arm_shift_q31
arm_shift_q15
arm_shift_q7
Vector Cast
arm_float_to_q31
Vector Cast
arm_float_to_q15
CMSIS function
Note
Vector Cast
arm_float_to_q7
Vector Cast
arm_q31_to_float
Vector Cast
arm_q31_to_q15
Vector Cast
arm_q31_to_q7
Vector Cast
arm_q15_to_float
Vector Cast
arm_q15_to_q31
Vector Cast
arm_q15_to_q7
Vector Cast
arm_q7_to_float
Vector Cast
arm_q7_to_q31
Vector Cast
arm_q7_to_q15
Vector Cast
arm_shift_q31
Vector Cast
arm_shift_q15
Vector Cast
arm_shift_q7
Square root
arm_sqrt_f32
Square root
arm_sqrt_q31
Square root
arm_sqrt_q15
9-51
Code Generation
9-52
Note
Operation
CMSIS function
sin
arm_sin_f32
cosine
arm_cos_f32
Complex Conjugate
arm_cmplx_conj_f32
Complex Conjugate
arm_cmplx_conj_q31
Complex Conjugate
arm_cmplx_conj_q15
Complex-by-Complex
Multiplication
arm_cmplx_mult_cmplx_f32
Complex-by-Complex
Multiplication
arm_cmplx_mult_cmplx_q31
Complex-by-Complex
Multiplication
arm_cmplx_mult_cmplx_q15
Complex-by-Real
Multiplication
arm_cmplx_mult_real_f32
Complex-by-Real
Multiplication
arm_cmplx_mult_real_q31
Complex-by-Real
Multiplication
arm_cmplx_mult_real_q15
10
Define New System Objects
Define Basic System Objects on page 10-3
Change Number of Step Inputs or Outputs on page 10-5
Specify System Block Input and Output Names on page 10-8
Validate Property and Input Values on page 10-10
Initialize Properties and Setup One-Time Calculations on page 10-13
Set Property Values at Construction Time on page 10-16
Reset Algorithm State on page 10-19
Define Property Attributes on page 10-21
Hide Inactive Properties on page 10-25
Limit Property Values to Finite String Set on page 10-27
Process Tuned Properties on page 10-30
Release System Object Resources on page 10-32
Define Composite System Objects on page 10-34
Define Finite Source Objects on page 10-38
Save System Object on page 10-40
Load System Object on page 10-43
Clone System Object on page 10-46
Define System Object Information on page 10-47
Define System Block Icon on page 10-49
Add Header to System Block Dialog on page 10-51
Add Property Groups to System Object and Block Dialog on page 10-53
10
10-2
System object.
edit AddOne.m
2 Subclass your object from matlab.System. Insert this line as the first line
of your file.
classdef AddOne < matlab.System
3 Add the stepImpl method, which contains the algorithm that runs when
users call the step method on your object. You always set the stepImpl
method access to protected because it is an internal method that users
do not directly call or run.
All methods, except static methods, expect the System object handle as the
first input argument. You can use any name for your System object handle.
In this example, instead of passing in the object handle, ~ is used to indicate
that the object handle is not used in the function. Using ~ instead of an
object handle prevents warnings about unused variables from occurring.
By default, the number of inputs and outputs are both one. To
change the number of inputs or outputs, use the getNumInputsImpl or
getNumOutputsImpl method, respectively.
methods (Access=protected)
function y = stepImpl(~, x)
y = x + 1;
end
end
10-3
10
Note Instead of manually creating your class definition file, you can use
an option on the New > System Object menu to open a template. The
Basic template opens a simple System object template. The Advanced
template includes more advanced features of System objects, such as backup
and restore. The Simulink Extension template includes additional
customizations of the System object for use in the Simulink MATLAB System
block. You then can edit the template file, using it as guideline, to create
your own System object.
10-4
See Also
Related
Examples
Concepts
Update the stepImpl method to accept a second input and provide a second
output.
methods (Access=protected)
function [y1,y2] = stepImpl(~,x1,x2)
y1 = x1 + 1
y2 = x2 + 1;
end
end
Update the Associated Methods
10-5
10
methods (Access=protected)
function numIn = getNumInputsImpl(~)
numIn = 2;
end
function numOut = getNumOutputsImpl(~)
numOut = 2;
end
end
Complete Class Definition File with Multiple Inputs and Outputs
10-6
See Also
getNumInputsImpl | getNumOutputsImpl
Related
Examples
Concepts
10-7
10
10-8
methods
function obj = MyCounter(varargin)
setProperties(obj,nargin,varargin{:});
end
end
methods (Access=protected)
function setupImpl(obj, u)
obj.Count = 0;
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj, u)
if (u > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function inputName = getInputNamesImpl(~)
inputName = 'source data';
end
function outputName = getOutputNamesImpl(~)
outputName = 'count';
end
end
end
See Also
Related
Examples
Concepts
10-9
10
This example shows how to validate the value of a single property using
set.PropertyName syntax. In this case, the PropertyName is Increment.
methods
% Validate the properties of the object
function set.Increment(obj,val)
if val >= 10
error('The increment value must be less than 10');
end
obj.Increment = val;
end
end
This example shows how to validate that the first input is a numeric value.
methods (Access=protected)
function validateInputsImpl(~,x)
if ~isnumeric(x)
10-10
10-11
10
if ~isnumeric(x)
error('Input must be numeric');
end
end
function out = stepImpl(obj,in)
if obj.UseIncrement
out = in + obj.Increment;
else
out = in + 1;
end
end
end
end
See Also
validateInputsImpl | validatePropertiesImpl
Related
Examples
Concepts
10-12
In this example, you define the public Filename property and specify the
value of that property as the nontunable string, default.bin. Users cannot
change nontunable properties after the setup method has been called. Refer
to the Methods Timing section for more information.
properties (Nontunable)
Filename ='default.bin'
end
Define Private Properties to Initialize
Users cannot access private properties directly, but only through methods of
the System object. In this example, you define the pFileID property as a
private property. You also define this property as hidden to indicate it is an
internal property that never displays to the user.
properties (Hidden,Access=private)
pFileID;
end
Define Setup
You use the setupImpl method to perform setup and initialization tasks. You
should include code in the setupImpl method that you want to execute one
time only. The setupImpl method is called once during the first call to the
step method. In this example, you allocate file resources by opening the
file for writing binary data.
methods
function setupImpl(obj,data)
obj.pFileID = fopen(obj.Filename,'wb');
10-13
10
if obj.pFileID < 0
error('Opening the file failed');
end
end
end
Although not part of setup, you should close files when your code is done using
them. You use the releaseImpl method to release resources.
Complete Class Definition File with Initialization and Setup
10-14
See Also
Related
Examples
Concepts
10-15
10
Define the System object constructor, which is a method that has the same
name as the class (MyFile in this example). Within that method, you use
the setProperties method to make all public properties available for input
when the user constructs the object. nargin is a MATLAB function that
determines the number of input arguments. varargin indicates all of the
objects public properties.
methods
function obj = MyFile(varargin)
setProperties(obj,nargin,varargin{:});
end
end
Complete Class Definition File with Constructor Setup
10-16
See Also
nargin | setProperties
10-17
10
Related
Examples
10-18
pCount is an internal counter property of the System object obj. The user
calls the reset method, which calls the resetImpl method. In this example
, pCount resets to 0.
Note When resetting an objects state, make sure you reset the size,
complexity, and data type correctly.
methods (Access=protected)
function resetImpl(obj)
obj.pCount = 0;
end
end
Complete Class Definition File with State Reset
10-19
10
obj.pCount = 0;
end
% The step method takes no inputs
function numIn = getNumInputsImpl(~)
numIn = 0;
end
end
end
end
See Also
Concepts
10-20
resetImpl
Use the nontunable attribute for a property when the algorithm depends on
the value being constant once data processing starts. Defining a property as
nontunable may improve the efficiency of your algorithm by removing the
need to check for or react to values that change. For code generation, defining
a property as nontunable allows the memory associated with that property
to be optimized. You should define all properties that affect the number of
input or output ports as nontunable.
System object users cannot change nontunable properties after the setup or
step method has been called. In this example, you define the InitialValue
property, and set its value to 0.
properties (Nontunable)
InitialValue = 0;
end
Specify Property as Logical
Logical properties have the value, true or false. System object users can
enter 1 or 0 or any value that can be converted to a logical. The value,
however, displays as true or false. You can use sparse logical values, but
they must be scalar values. In this example, the Increment property indicates
whether to increase the counter. By default, Increment is tunable property.
The following restrictions apply to a property with the Logical attribute,
Cannot also be Dependent or PositiveInteger
Default value must be true or false. You cannot use 1 or 0 as a default
value.
10-21
10
properties (Logical)
Increment = true
end
Specify Property as Positive Integer
If your algorithm uses properties that hold state, you can assign those
properties the DiscreteState attribute . Properties with this attribute
display their state values when users call getDiscreteStateImpl via the
getDiscreteState method. The following restrictions apply to a property
with the DiscreteState attribute,
Numeric, logical, or fi value, but not a scaled double fi value
Does not have any of these attributes: Nontunable, Dependent, Abstract,
Constant, or Transient.
No default value
Not publicly settable
GetAccess=Public by default
Value set only using the setupImpl method or when the System object is
locked during resetImpl or stepImpl
In this example, you define the Count property.
properties (DiscreteState)
Count;
10-22
end
Complete Class Definition File with Property Attributes
10-23
10
end
% The step method takes no inputs
function numIn = getNumInputsImpl(~)
numIn = 0;
end
end
end
Concepts
10-24
Class Attributes
Property Attributes
What You Cannot Change While Your System Is Running
Methods Timing on page 10-75
10-25
10
See Also
10-26
isInactivePropertyImpl
String sets use two related properties. You first specify the user-visible
property name and default string value. Then, you specify the associated
hidden property by appending Set to the property name. You must use
a capital S in Set.
In the Set property, you specify the valid string values as a cell array of the
matlab.system.Stringset class. This example uses Color and ColorSet
as the associated properties.
properties
Color = 'blue'
end
properties (Hidden,Transient)
ColorSet = matlab.system.StringSet({'red','blue','green'});
end
Complete Class Definition File with String Set
10-27
10
methods(Access = protected)
function stepImpl(obj)
h = Whiteboard.getWhiteboard();
plot(h, ...
randn([2,1]),randn([2,1]), ...
'Color',obj.Color(1));
end
function releaseImpl(obj)
cla(Whiteboard.getWhiteboard());
hold('on');
end
function n = getNumInputsImpl(~)
n = 0;
end
function n = getNumOutputsImpl(~)
n = 0;
end
end
methods (Static)
function a = getWhiteboard()
h = findobj('tag','whiteboard');
if isempty(h)
h = figure('tag','whiteboard');
hold('on');
end
a = gca;
end
end
end
%%
% Each call to step draws lines on a whiteboard
%% Construct the System object
hGreenInk = Whiteboard;
hBlueInk = Whiteboard;
10-28
See Also
matlab.system.StringSet
10-29
10
10-30
See Also
processTunedPropertiesImpl
10-31
10
This method allows you to clear the axes on the Whiteboard figure window
while keeping the figure open.
methods
function releaseImpl(obj)
cla(Whiteboard.getWhiteboard());
hold('on');
end
end
Complete Class Definition File with Released Resources
10-32
end
function releaseImpl(obj)
cla(Whiteboard.getWhiteboard());
hold('on');
end
function n = getNumInputsImpl(~)
n = 0;
end
function n = getNumOutputsImpl(~)
n = 0;
end
end
methods (Static)
function a = getWhiteboard()
h = findobj('tag','whiteboard');
if isempty(h)
h = figure('tag','whiteboard');
hold('on');
end
a = gca;
end
end
end
See Also
Related
Examples
releaseImpl
10-33
10
To define a System object from other System objects, store those objects in
your class definition file as properties. In this example, FIR and IIR are
separate System objects defined in their own class-definition files. You use
those two objects to calculate the pFir and pIir property values.
properties (Nontunable, Access = private)
pFir % store the FIR filter
pIir % store the IIR filter
end
methods
function obj = Filter(varargin)
setProperties(obj, nargin, varargin{:});
obj.pFir = FIR(obj.zero);
obj.pIir = IIR(obj.pole);
end
end
Complete Class Definition File of Composite System Object
10-34
end
properties (Nontunable,Access=private)
pZero % store the FIR filter
pPole % store the IIR filter
end
methods
function obj = Filter(varargin)
setProperties(obj,nargin, varargin{:});
% Create instances of FIR and IIR as
% private properties
obj.pZero = Zero(obj.zero);
obj.pPole = Pole(obj.pole);
end
end
methods (Access=protected)
function setupImpl(obj,x)
setup(obj.pZero,x);
setup(obj.pPole,x);
end
function resetImpl(obj)
reset(obj.pZero);
reset(obj.pPole);
end
function y = stepImpl(obj,x)
y = step(obj.pZero,x) + step(obj.pPole,x);
end
function releaseImpl(obj)
release(obj.pZero);
release(obj.pPole);
end
end
end
Class Definition File for IIR Component of Filter
10-35
10
10-36
end
end
methods (Access=protected)
function y = stepImpl(obj,x)
y = x + obj.tap * obj.Num;
obj.tap = x;
end
end
end
See Also
nargin
10-37
10
10-38
y = 0;
end
end
function bDone = isDoneImpl(obj)
bDone = obj.NumSteps==2;
end
end
methods (Access=protected)
function n = getNumInputsImpl(~)
n = 0;
end
function n = getNumOutputsImpl(~)
n = 1;
end
end
end
See Also
Concepts
matlab.system.mixin.FiniteSource
10-39
10
10-40
end
properties (Dependent)
dependentprop
end
methods
function obj = MySaveLoader(varargin)
[email protected]();
setProperties(obj, nargin, varargin{:});
end
end
methods(Access = protected)
function setupImpl(obj, varargin)
obj.state = 42;
end
function out = stepImpl(obj, in)
obj.state = in;
out = obj.state;
end
end
% Serialization
methods(Access=protected)
function s = saveObjectImpl(obj)
% Call the base class method
s = [email protected](obj);
% Save the child System objects
s.child = matlab.System.saveObject(obj.child);
% Save the protected & private properties
s.protected = obj.protected;
s.pdependentprop = obj.pdependentprop;
% Save the state only if object locked
if isLocked(obj)
10-41
10
s.state = obj.state;
end
end
function loadObjectImpl(obj,s,wasLocked)
% Load child System objects
obj.child = matlab.System.loadObject(s.child);
% Load protected and private properties
obj.protected = s.protected;
obj.pdependentprop = s.pdependentprop;
% Load the state only if object locked
if wasLocked
obj.state = s.state;
end
% Call base class method to load public properties
[email protected](obj,s,wasLocked);
end
end
end
See Also
saveObjectImpl | loadObjectImpl
Related
Examples
10-42
10-43
10
state
end
properties (Dependent)
dependentprop
end
methods
function obj = MySaveLoader(varargin)
[email protected]();
setProperties(obj, nargin, varargin{:});
end
end
methods(Access = protected)
function setupImpl(obj,varargin)
obj.state = 42;
end
function out = stepImpl(obj,in)
obj.state = in;
out = obj.state;
end
end
% Serialization
methods(Access=protected)
function s = saveObjectImpl(obj)
% Call the base class method
s = [email protected](obj);
% Save the child System objects
s.child = matlab.System.saveObject(obj.child);
% Save the protected & private properties
s.protected = obj.protected;
s.pdependentprop = obj.pdependentprop;
% Save the state only if object locked
10-44
if isLocked(obj)
s.state = obj.state;
end
end
function loadObjectImpl(obj,s,wasLocked)
% Load child System objects
obj.child = matlab.System.loadObject(s.child);
% Load protected and private properties
obj.protected = s.protected;
obj.pdependentprop = s.pdependentprop;
% Load the state only if object locked
if wasLocked
obj.state = s.state;
end
% Call base class method to load public properties
[email protected](obj,s,wasLocked);
end
end
end
See Also
saveObjectImpl | loadObjectImpl
Related
Examples
10-45
10
You can define your own clone method, which is useful for copying objects
without saving their state. The default cloneImpl method copies both a
System object and its current state. If an object is locked, the default
cloneImpl creates a cloned object that is also locked. An example of when you
may want to write your own clone method is for cloning objects that handle
resources. These objects cannot allocate resources twice and you would not
want to save their states. To write your clone method, use the saveObject
and loadObject methods to perform the clone within the cloneImpl method.
methods(Access=protected)
function obj2 = cloneImpl(obj1)
s = saveObject (obj1);
obj2 = loadObject(s);
end
end
Complete Class Definition File with Clone
See Also
10-46
You can define your own info method to display specific information for
your System object. The default infoImpl method returns an empty struct.
This infoImpl method returns detailed information when the info method
is called using info(x,'details') or only count information if it is called
using info(x).
methods (Access=protected)
function s = infoImpl(obj,varargin)
if nargin>1 && strcmp('details',varargin(1))
s = struct('Name','Counter',...
'Properties', struct('CurrentCount', ...
obj.pCount,'Threshold',obj.Threshold));
else
s = struct('Count',obj.pCount);
end
end
end
Complete Class Definition File with InfoImpl
10-47
10
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj, u)
if (u > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function s = infoImpl(obj,varargin)
if nargin>1 && strcmp('details',varargin(1))
s = struct('Name','Counter',...
'Properties', struct('CurrentCount', ...
obj.pCount,'Threshold',obj.Threshold));
else
s = struct('Count',obj.pCount);
end
end
end
See Also
10-48
infoImpl
10-49
10
methods (Access=protected)
function setupImpl(obj, u)
obj.Count = 0;
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj, u)
if (u > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function icon = getIconImpl(~)
icon = sprintf('New\nCounter');
end
end
end
See Also
getIconImpl | matlab.system.mixin.CustomIcon
Concepts
10-50
This example shows how to use getHeaderImpl to specify a panel title and
text for the MyCounter System object.
If you do not specify the getHeaderImpl, the block does not display any title
or text for the panel.
You always set the getHeaderImpl method access to protected because it is
an internal method that end users do not directly call or run.
methods(Static,Access=protected)
function header = getHeaderImpl
header = matlab.system.display.Header('MyCounter',...
'Title','My Enhanced Counter');
end
end
Complete Class Definition File with Defined Header
10-51
10
See Also
10-52
getHeaderImpl | matlab.system.display.Header
10-53
10
10-54
upperGroup = matlab.system.display.Section(...
'Title', 'Upper threshold', ...
'PropertyList',{'UpperThreshold'});
lowerGroup = matlab.system.display.Section(...
'Title','Lower threshold', ...
'PropertyList',{'UseLowerThreshold','LowerThreshold'});
thresholdGroup = matlab.system.display.SectionGroup(...
'Title', 'Parameters', ...
'Sections', [upperGroup,lowerGroup]);
valuesGroup = matlab.system.display.SectionGroup(...
'Title', 'Initial conditions', ...
'PropertyList', {'StartValue'});
groups = [thresholdGroup, valuesGroup];
end
end
methods(Access=protected)
function setupImpl(obj, ~, ~)
obj.Count = obj.StartValue;
end
function y = stepImpl(obj,u)
if obj.UseLowerThreshold
if (u > obj.UpperThreshold) || ...
(u < obj.LowerThreshold)
obj.Count = obj.Count + 1;
end
else
if (u > obj.UpperThreshold)
obj.Count = obj.Count + 1;
end
end
y = obj.Count;
end
function resetImpl(obj)
obj.Count = obj.StartValue;
end
10-55
10
See Also
getPropertyGroupsImpl | matlab.system.display.Section |
matlab.system.display.SectionGroup
Concepts
10-56
To use the getOutputSizeImpl method, you must subclass from both the
matlab.System base class and the Propagates mixin class.
classdef CounterReset < matlab.System & ...
matlab.system.mixin.Propagates
Specify Output Size
10-57
10
function y = stepImpl(obj,u1,u2)
% Add to count if u1 is above threshold
% Reset if u2 is true
if (u2)
obj.Count = 0;
elseif (u1 > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function resetImpl(obj)
obj.Count = 0;
end
function N = getNumInputsImpl(~)
N = 2;
end
function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name)
if strcmp(name,'Count')
sz = [1 1];
dt = 'double';
cp = false;
else
error(['Error: Incorrect State Name: 'name'.']);
end
end
function dataout = getOutputDataTypeImpl(~)
dataout = 'double';
end
function sizeout = getOutputSizeImpl(~)
sizeout = [1 1];
end
function cplxout = isOutputComplexImpl(~)
cplxout = false;
end
function fixedout = isOutputFixedSizeImpl(~)
fixedout = true;
10-58
end
end
end
See Also
matlab.system.mixin.Propagates | getOutputSizeImpl
Concepts
10-59
10
10-60
obj.Count = 0;
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj,u1,u2)
% Add to count if u1 is above threshold
% Reset if u2 is true
if (u2)
obj.Count = 0;
elseif (u1 > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function N = getNumInputsImpl(~)
N = 2;
end
function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name)
if strcmp(name,'Count')
sz = [1 1];
dt = 'double';
cp = false;
else
error(['Error: Incorrect State Name: 'name'.']);
end
end
function dataout = getOutputDataTypeImpl(~)
dataout = 'double';
end
function sizeout = getOutputSizeImpl(~)
sizeout = [1 1];
end
function cplxout = isOutputComplexImpl(~)
cplxout = false;
end
10-61
10
See Also
matlab.system.mixin.Propagates | getOutputDataTypeImpl
Concepts
10-62
To use the isOutputComplexImpl method, you must subclass from both the
matlab.System base class and the Propagates mixin class.
classdef CounterReset < matlab.System & ...
matlab.system.mixin.Propagates
Specify Output Complexity
10-63
10
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj,u1,u2)
% Add to count if u1 is above threshold
% Reset if u2 is true
if (u2)
obj.Count = 0;
elseif (u1 > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function N = getNumInputsImpl(~)
N = 2;
end
function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name)
if strcmp(name,'Count')
sz = [1 1];
dt = 'double';
cp = false;
else
error(['Error: Incorrect State Name: 'name'.']);
end
end
function dataout = getOutputDataTypeImpl(~)
dataout = 'double';
end
function sizeout = getOutputSizeImpl(~)
sizeout = [1 1];
end
function cplxout = isOutputComplexImpl(~)
cplxout = false;
end
function fixedout = isOutputFixedSizeImpl(~)
10-64
fixedout = true;
end
end
end
See Also
matlab.system.mixin.Propagates | isOutputComplexImpl
Concepts
10-65
10
To use the isOutputFixedSizeImpl method, you must subclass from both the
matlab.System base class and the Propagates mixin class.
classdef CounterReset < matlab.System & ...
matlab.system.mixin.Propagates
Specify Output as Fixed Size
10-66
obj.Count = 0;
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj,u1,u2)
% Add to count if u1 is above threshold
% Reset if u2 is true
if (u2)
obj.Count = 0;
elseif (u1 > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function N = getNumInputsImpl(~)
N = 2;
end
function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name)
if strcmp(name,'Count')
sz = [1 1];
dt = 'double';
cp = false;
else
error(['Error: Incorrect State Name: 'name'.']);
end
end
function dataout = getOutputDataTypeImpl(~)
dataout = 'double';
end
function sizeout = getOutputSizeImpl(~)
sizeout = [1 1];
end
function cplxout = isOutputComplexImpl(~)
cplxout = false;
end
10-67
10
See Also
matlab.system.mixin.Propagates | isOutputFixedSizeImpl
Concepts
10-68
10-69
10
Count
end
methods (Access=protected)
function setupImpl(obj,~,~)
obj.Count = 0;
end
function resetImpl(obj)
obj.Count = 0;
end
function y = stepImpl(obj,u1,u2)
% Add to count if u1 is above threshold
% Reset if u2 is true
if (u2)
obj.Count = 0;
elseif (u1 > obj.Threshold)
obj.Count = obj.Count + 1;
end
y = obj.Count;
end
function N = getNumInputsImpl(~)
N = 2;
end
function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name)
sz = [1 1];
dt = 'double';
cp = false;
end
function dataout = getOutputDataTypeImpl(~)
dataout = 'double';
end
function sizeout = getOutputSizeImpl(~)
sizeout = [1 1];
end
function cplxout = isOutputComplexImpl(~)
cplxout = false;
10-70
end
function fixedout = isOutputFixedSizeImpl(~)
fixedout = true;
end
end
end
See Also
matlab.system.mixin.Propagates | getDiscreteStateSpecificationImpl
Concepts
10-71
10
10-72
methods(Access=protected)
function validatePropertiesImpl(obj)
if ((numel(obj.NumDelays)>1) || (obj.NumDelays <= 0))
error('Number of delays must be positive non-zero scalar value.
end
if (numel(obj.InitialOutput)>1)
error('Initial Output must be scalar value.');
end
end
function setupImpl(obj, ~)
obj.PreviousInput = ones(1,obj.NumDelays)*obj.InitialOutput;
end
function resetImpl(obj)
10-73
10
obj.PreviousInput = ones(1,obj.NumDelays)*obj.InitialOutput;
end
function [y] = outputImpl(obj, ~)
y = obj.PreviousInput(end);
end
function updateImpl(obj, u)
obj.PreviousInput = [u obj.PreviousInput(1:end-1)];
end
function flag = isInputDirectFeedthroughImpl(~,~)
flag = false;
end
end
end
See Also
Concepts
10-74
Methods Timing
Methods Timing
In this section...
Setup Method Call Sequence on page 10-75
Step Method Call Sequence on page 10-76
Reset Method Call Sequence on page 10-76
Release Method Call Sequence on page 10-77
10-75
10
10-76
Methods Timing
See Also
Related
Examples
Concepts
10-77
10
10-78
10-79
10
10-80
11
Links to Category Pages
Signal Management Library on page 11-2
Sinks Library on page 11-3
Math Functions Library on page 11-4
Filtering Library on page 11-5
11
11-2
Sinks Library
Sinks Library
You can find the relevant blocks in the following pages:
Signal Import and Export
Scopes and Data Logging
11-3
11
11-4
Filtering Library
Filtering Library
You can find the relevant blocks in the following pages:
Filter Design
Single-Rate Filters
Multirate and Multistage Filters
Adaptive Filters
11-5
11
11-6
12
Designing Lowpass FIR
Filters
Lowpass FIR Filter Design on page 12-2
Controlling Design Specifications in Lowpass FIR Design on page 12-7
Designing Filters with Non-Equiripple Stopband on page 12-13
Minimizing Lowpass FIR Filter Length on page 12-18
12
FIR filters are widely used due to the powerful design algorithms that exist
for them, their inherent stability when implemented in non-recursive form,
the ease with which one can attain linear phase, their simple extensibility
to multirate cases, and the ample hardware support that exists for them
among other reasons. This example showcases functionality in the DSP
System Toolbox for the design of low pass FIR filters with a variety of
characteristics. Many of the concepts presented here can be extended to other
responses such as highpass, bandpass, etc.
Consider a simple design of a lowpass filter with a cutoff frequency of 0.4*pi
radians per sample:
Fc = 0.4;
N = 100;
Hf = fdesign.lowpass('N,Fc',N,Fc);
We can design this lowpass filter using the window method. For example, we
can use a Hamming window or a Dolph-Chebyshev window:
Hd1 = design(Hf,'window','window',@hamming,'systemobject',true);
Hd2 = design(Hf,'window','window',{@chebwin,50}, ...
'systemobject',true);
hfvt = fvtool(Hd1,Hd2,'Color','White');
legend(hfvt,'Hamming window design', ...
'Dolph-Chebyshev window design')
12-2
The choice of filter was arbitrary. Since ideally the order should be infinite, in
general, a larger order results in a better approximation to ideal at the expense
of a more costly implementation. For instance, with a Dolph-Chebyshev
window, we can decrease the transition region by increasing the filter order:
Hf.FilterOrder = 200;
Hd3 = design(Hf,'window','window',{@chebwin,50},...
'systemobject',true);
hfvt2 = fvtool(Hd2,Hd3,'Color','White');
legend(hfvt2,'Dolph-Chebyshev window design. Order = 100',...
'Dolph-Chebyshev window design. Order = 200')
12-3
12
We can still use the window method, along with a Kaiser window, to design
the low pass filter.
Hd4 = design(Hf,'kaiserwin','systemobject',true);
measure(Hd4)
12-4
ans =
Sampling Frequency
Passband Edge
3-dB Point
6-dB Point
Stopband Edge
Passband Ripple
Stopband Atten.
Transition Width
:
:
:
:
:
:
:
:
One thing to note is that the transition width as specified is centered around
the cutoff frequency of 0.4 pi. This will become the point at which the gain of
the lowpass filter is half the passband gain (or the point at which the filter
reaches 6 dB of attenuation).
Optimal Minimum Order Designs
The Kaiser window design is not an optimal design and as a result the filter
order required to meet the specifications using this method is larger than it
needs to be. Equiripple designs result in the lowpass filter with the smallest
possible order to meet a set of specifications.
Hd5 = design(Hf,'equiripple','systemobject',true);
hfvt3 = fvtool(Hd4,Hd5,'Color','White');
legend(hfvt3,'Kaiser window design','Equiripple design')
12-5
12
In this case, 146 coefficients are needed by the equiripple design while 183
are needed by the Kaiser window design.
12-6
Set the number of coefficients to 101, which means setting the order to 100:
N = 100;
% order = 100 -> 101 coefficients
Fc = 0.4;
setspecs(Hf,'N,Fc,Ap,Ast',N,Fc,Ap,Ast);
12-7
12
Measure the filter variables of the second equiripple filter, and compare the
graphs of the first and second filters:
measure(Hd2)
hfvt = fvtool(Hd1,Hd2,'Color','White');
legend(hfvt,'Equiripple design, 146 coeffcients', ...
'Equiripple design, 101 coefficients')
Sampling Frequency
Passband Edge
3-dB Point
6-dB Point
Stopband Edge
Passband Ripple
Stopband Atten.
Transition Width
:
:
:
:
:
:
:
:
Notice that the transition has increased by almost 50%. This is not surprising
given the almost 50% difference between 101 coefficients and 146 coefficients.
Controlling the Transition Region Width
12-8
:
:
:
:
:
:
:
:
12-9
12
Note that in this case, the differences between using 146 coefficients and
using 101 coefficients is reflected in a larger passband ripple and a smaller
stopband attenuation.
It is possible to increase the attenuation in the stopband while keeping the
same filter order and transition width by the use of weights. Weights are
a way of specifying the relative importance of the passband ripple versus
the stopband attenuation. By default, passband and stopband are equally
weighted (a weight of one is assigned to each). If we increase the stopband
weight, we can increase the stopband attenuation at the expense of increasing
the stopband ripple as well.
Hd4 = design(Hf,'equiripple','Wstop',5,'systemobject',true);
measure(Hd4)
hfvt3 = fvtool(Hd3,Hd4,'Color','White');
legend(hfvt3,'Passband weight = 1, Stopband weight = 1',...
'Passband weight = 1, Stopband weight = 5')
Sampling Frequency
Passband Edge
3-dB Point
6-dB Point
Stopband Edge
Passband Ripple
Stopband Atten.
Transition Width
12-10
:
:
:
:
:
:
:
:
12-11
12
12-12
To start, set up the filter parameters and use fdesign to create a constructor
for designing the filter.
N = 100;
Fp = 0.38;
Fst = 0.42;
Hf = fdesign.lowpass('N,Fp,Fst',N,Fp,Fst);
12-13
12
Notice how the attenuation in the stopband increases with frequency for the
least-squares designs while it remains constant for the equiripple design.
The increased attenuation in the least-squares case minimizes the energy in
that band of the signal to be filtered.
Equiripple Designs with Increasing Stopband Attenuation
12-14
Notice that the stopbands are quite similar. However the equiripple design
has a significantly smaller passband ripple,
mls = measure(Hd2);
meq = measure(Hd3);
mls.Apass
meq.Apass
ans =
0.3504
ans =
0.1867
Filters with a stopband that decays as (1/f)^M will decay at 6M dB per octave.
Another way of shaping the stopband is using a linear decay. For example
12-15
12
Hd4 = design(Hf,'equiripple','StopbandShape','linear',...
'StopbandDecay',53.333,'systemobject',true);
hfvt3 = fvtool(Hd3,Hd4,'Color','White');
legend(hfvt3,'Equiripple design with stopband decaying as (1/f)^4',...
'Equiripple design with stopband decaying linearly and a slope of 53.
12-16
=
=
=
=
=
100;
2; % number of bands
[0 .38 .42:.02:1];
[1 1 zeros(1,length(F)-2)];
linspace(1,100,length(F)-2);
Harb = fdesign.arbmag('N,B,F,A',N,B,F(1:2),A(1:2),F(3:end),...
A(3:end));
Ha = design(Harb,'equiripple','B2Weights',W,...
'systemobject',true);
fvtool(Ha,'Color','White')
12-17
12
To start, set up the filter parameters and use fdesign to create a constructor
for designing the filter.
N = 100;
Fp = 0.38;
Fst = 0.42;
Ap = 0.06;
Ast = 60;
Hf = fdesign.lowpass('Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast);
12-18
Notice that the number of coefficients has been reduced from 146 to 117. As
a second example, consider the design with a stopband decaying in linear
fashion. Notice the increased stopband attenuation. The passband ripple
is also significantly smaller.
setspecs(Hf,'N,Fp,Fst',N,Fp,Fst);
Hd3 = design(Hf,'equiripple','StopbandShape','linear',...
'StopbandDecay',53.333,'systemobject',true);
setspecs(Hf,'Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast);
Hd4 = design(Hf,'equiripple','StopbandShape','linear',...
'StopbandDecay',53.333,'minphase',true,'systemobject',true);
hfvt2 = fvtool(Hd3,Hd4,'Color','White');
legend(hfvt2,'Linear-phase equiripple design with linearly decaying stopb
'Minimum-phase equiripple design with linearly decaying stopband')
12-19
12
12-20
The number of nonzero coefficients required in the IFIR case is 111. Less than
both the equiripple linear-phase and minimum-phase designs.
12-21
12
12-22
13
FDATool: A Filter Design
and Analysis GUI
Overview on page 13-2
Using FDATool on page 13-6
Importing a Filter Design on page 13-39
13
Overview
In this section...
FDATool on page 13-2
Filter Design Methods on page 13-2
Using the Filter Design and Analysis Tool on page 13-4
Analyzing Filter Responses on page 13-4
Filter Design and Analysis Tool Panels on page 13-4
Getting Help on page 13-5
FDATool
The Filter Design and Analysis Tool (FDATool) is a user interface for
designing and analyzing filters quickly. FDATool enables you to design digital
FIR or IIR filters by setting filter specifications, by importing filters from
your MATLAB workspace, or by adding, moving or deleting poles and zeros.
FDATool also provides tools for analyzing filters, such as magnitude and
phase response and pole-zero plots.
13-2
Design Method
Function
Butterworth
butter
Chebyshev Type I
cheby1
Chebyshev Type II
cheby2
Elliptic
ellip
Maximally Flat
maxflat
Equiripple
firpm
Least-squares
firls
Overview
Design Method
Function
Constrained least-squares
fircls
Complex equiripple
cfirpm
Window
fir1
When using the window method in FDATool, all Signal Processing Toolbox
window functions are available, and you can specify a user-defined window by
entering its function name and input parameter.
Function
firceqrip
fircband
firgr
firhalfband
firlpnorm
firnyquist
Interpolated FIR
ifir
iircomb
iirgrpdelay
iirlpnorm
iirlpnormc
iirnotch
iirpeak
13-3
13
13-4
Overview
Import previously saved filters or filter coefficients that you have stored
in the MATLAB workspace.
Pole/Zero Editor. See Editing the Filter Using the Pole/Zero Editor on
page 13-19. You use this panel to add, delete, and move poles and zeros
in your filter design.
If you also have DSP System Toolbox product installed, additional panels
are available:
Set quantization parameters Use this panel to quantize double-precision
filters that you design in FDATool, quantize double-precision filters that
you import into FDATool, and analyze quantized filters.
Transform filter Use this panel to change a filter from one response
type to another.
Multirate filter design Use this panel to create a multirate filter
from your existing FIR design, create CIC filters, and linear and hold
interpolators.
If you have Simulink installed, this panel is available:
Realize Model Use this panel to create a Simulink block containing the
filter structure.
Getting Help
At any time, you can right-click or click the Whats this? button,
, to get
information on the different parts of the tool. You can also use the Help
menu to see complete Help information.
13-5
13
Using FDATool
To open FDATool, type
fdatool
Note that when you open FDATool, Design Filter is not enabled. You must
make a change to the default filter design in order to enable Design Filter.
This is true each time you want to change the filter design. Changes to
radio button items or drop down menu items such as those under Response
Type or Filter Order enable Design Filter immediately. Changes to
specifications in text boxes such as Fs, Fpass, and Fstop require you to click
outside the text box to enable Design Filter.
13-6
Using FDATool
Note Not all filter design methods are available for all response types. Once
you choose your response type, this may restrict the filter design methods
available to you. Filter design methods that are not available for a selected
response type are removed from the Design Method region of the GUI.
13-7
13
13-8
Using FDATool
Filter Order
You have two mutually exclusive options for determining the filter order
when you design an equiripple filter:
Specify order: You enter the filter order in a text box.
Minimum order: The filter design method determines the minimum
order filter.
Select the Minimum order radio button for this example.
Note that filter order specification options depend on the filter design method
you choose. Some filter methods may not have both options available.
Options
The available options depend on the selected filter design method. Only
the FIR Equiripple and FIR Window design methods have settable options.
13-9
13
For FIR Equiripple, the option is a Density Factor. See firpm for more
information. For FIR Window the options are Scale Passband, Window
selection, and for the following windows, a settable parameter:
Window
Parameter
Chebyshev (chebwin)
Sidelobe attenuation
Gaussian (gausswin)
Alpha
Kaiser (kaiser)
Beta
Taylor (taylorwin)
Tukey (tukeywin)
Alpha
User Defined
You can view the window in the Window Visualization Tool (wvtool) by
clicking the View button.
For this example, set the Density factor to 16.
13-10
Hz
kHz
MHz
Normalized (0 to 1)
Using FDATool
Sampling frequency
Passband frequencies
Stopband frequencies
You specify the passband with two frequencies. The first frequency
determines the lower edge of the passband, and the second frequency
determines the upper edge of the passband.
Similarly, you specify the stopband with two frequencies. The first frequency
determines the upper edge of the first stopband, and the second frequency
determines the lower edge of the second stopband.
For this example:
Keep the units in Hz (default).
Set the sampling frequency (Fs) to 2000 Hz.
Set the end of the first stopband (Fstop1) to 200 Hz.
Set the beginning of the passband (Fpass1) to 300 Hz.
Set the end of the passband (Fpass2) to 700 Hz.
Set the beginning of the second stopband (Fstop2) to 800 Hz.
13-11
13
13-12
Using FDATool
13-13
13
y-axis is added to the right side of the response plot. (Note that not all
responses can be overlaid on each other.)
You can also display the filter coefficients and detailed filter information in
this region.
For all the analysis methods, except zero-phase response, you can access
them from the Analysis menu, the Analysis Parameters dialog box from the
context menu, or by using the toolbar buttons. For zero-phase, right-click the
y-axis of the plot and select Zero-phase from the context menu.
For example, to look at the filters magnitude response, select the Magnitude
Response button
on the toolbar.
You can also overlay the filter specifications on the Magnitude plot by
selecting View > Specification Mask.
Note You can use specification masks in FVTool only if FVTool was launched
from FDATool.
13-14
Using FDATool
For information on using data tips, see Data Cursor Displaying Data
Values Interactively in the MATLAB documentation.
13-15
13
13-16
Using FDATool
To change the filter name, type the new name in Filter name. (In fvtool,
if you have multiple filters, select the desired filter and then enter the new
name.)
To change the sampling frequency, select the desired unit from Units and
enter the sampling frequency in Fs. (For each filter in fvtool, you can specify
a different sampling frequency or you can apply the sampling frequency to all
filters.)
13-17
13
To save the displayed parameters as the default values to use when FDATool
or FVTool is opened, click Save as Default.
To restore the default values, click Restore Original Defaults.
13-18
Using FDATool
13-19
13
Note You cannot generate MATLAB code (File > Generate MATLAB
code) if your filter was designed or edited with the Pole/Zero Editor.
You cannot move quantized poles and zeros. You can only move the reference
poles and zeros.
Click the Pole/Zero Editor button in the sidebar or select Edit > Pole/Zero
Editor to display this panel.
Poles are shown using x symbols and zeros are shown using o symbols.
13-20
Using FDATool
these buttons from left to right: move pole, add pole, add zero, and delete
pole or zero.
The following plot parameters and controls are located to the left of the
pole/zero plot and below the plot mode buttons.
Filter gain factor to compensate for the filters pole(s) and zero(s) gains
Coordinates units (Polar or Rectangular) of the selected pole or zero
Magnitude if polar coordinates is selected, magnitude of the selected
pole or zero
Angle if polar coordinates is selected, angle of selected pole(s) or zero(s)
Real if rectangular coordinates is selected, real component of selected
pole(s) or zero(s)
Imaginary if rectangular coordinates is selected, imaginary component
of selected pole or zero
Section for multisection filters, number of the current section
Conjugate creates a corresponding conjugate pole or zero or
automatically selects the conjugate pole or zero if it already exists.
Auto update immediately updates the displayed magnitude response
when poles or zeros are added, moved, or deleted.
The Edit > Pole/Zero Editor has items for selecting multiple poles/zeros,
for inverting and mirroring poles/zeros, and for deleting, scaling and rotating
poles/zeros.
13-21
13
Moving one of the zeros on the vertical axis produces the following result:
13-22
Using FDATool
13-23
13
Direct-form I
Direct-form II
Direct-form I transposed
Direct-form II transposed
Lattice ARMA
Note If you have DSP System Toolbox product installed, you will see
additional structures in the Convert structure dialog box.
In addition, the following conversions are available for particular classes
of filters:
Minimum phase FIR filters can be converted to Lattice minimum phase
Maximum phase FIR filters can be converted to Lattice maximum phase
Allpass filters can be converted to Lattice allpass
IIR filters can be converted to Lattice ARMA
Note Converting from one filter structure to another may produce a result
with different characteristics than the original. This is due to the computers
finite-precision arithmetic and the variations in the conversions roundoff
computations.
For example:
Select Edit > Convert Structure to open the Convert structure dialog box.
Select Direct-form I in the list of filter structures.
13-24
Using FDATool
13-25
13
13-26
Using FDATool
For objects, assign the variable name in the Discrete Filter (or
Quantized Filter) text box. If you have variables with the same names
in your workspace and you want to overwrite them, select the Overwrite
Variables check box.
5 Click the Export button.
13-27
13
box appears.
4 Choose or enter a filename and click the Save button.
The coefficients are saved in the text file that you specified, and the MATLAB
Editor opens to display the file. The text file also contains comments with the
MATLAB version number, the Signal Processing Toolbox version number,
and filter information.
13-28
Using FDATool
Exporting to SPTool
You may want to use your designed filter in SPTool to do signal processing
and analysis.
1 Select File > Export. The Export dialog box appears.
2 Select SPTool from the Export To menu.
3 Assign the variable name in the Discrete Filter (or Quantized Filter)
text box. If you have variables with the same names in your workspace and
you want to overwrite them, select the Overwrite Variables check box.
4 Click the Export button.
SPTool opens and the current FDATool filter appears in the Filter area list
as the specified variable name followed by (Imported).
Note If you are using the DSP System Toolbox software and export a
quantized filter, only the values of its quantized coefficients are exported.
The reference coefficients are not exported. SPTool does not restrict the
coefficient values, so if you edit them in SPTool by moving poles or zeros,
the filter will no longer be in quantized form.
File > Export to Simulink Model. The Realize Model panel is displayed.
13-29
13
model, set the Destination to Current. To inset the block into a new
model, select New. To insert the block into a user-defined subsystem, select
User defined.
4 If you want to overwrite a block previously created from this panel, check
13-30
Using FDATool
Optimization Effects
Note The Build model using basic elements check box is enabled
only when you have a DSP System Toolbox license and your filter can be
designed using a Digital Filter block. For more information, see the Filter
Realization Wizard topic in the DSP System Toolbox documentation.
6 Set the Input processing parameter to specify whether the generated
13-31
13
on the type of filter you design, one or both of the following options may
be available:
Columns as channels (frame based) When you select this option,
the block treats each column of the input as a separate channel.
Elements as channels (sample based) When you select this
option, the block treats each element of the input as a separate channel.
7 Click the Realize Model button to create the filter block. When the Build
box appears.
13-32
Using FDATool
2 Enter the variable names to be used in the C header file. The particular
filter structure determines the variables that are created in the file
Filter Structure
Variable Parameter
Direct-form I
Direct-form II
Direct-form I
transposed
Direct-form II
transposed
Lattice ARMA
Lattice MA
Direct-form FIR
Direct-form FIR
transposed
13-33
13
file, but leave the dialog box open for additional C header file definitions.
%
% MATLAB Code
% Generated by MATLAB(R) 7.11 and the Signal Processing Toolbox 6.14.
%
% Generated on: 17-Feb-2010 14:15:37
13-34
Using FDATool
% Sampling Frequency
Fpass = 9600;
% Passband Frequency
Fstop = 12000;
% Stopband Frequency
Dpass = 0.057501127785;
% Passband Ripple
Dstop = 0.0001;
% Stopband Attenuation
dens
% Density Factor
= 20;
Hd = dfilt.dffir(b);
% [EOF]
13-35
13
Store Filter Displays the Store Filter dialog box in which you specify the
filter name to use when storing the filter in the Filter Manager. The default
name is the type of the filter.
13-36
Using FDATool
The current filter is listed below the listbox. To change the current filter,
highlight the desired filter. If you select Edit current filter, FDATool
displays the currently selected filter specifications. If you make any changes
to the specifications, the stored filter is updated immediately.
To cascade two or more filters, highlight the desired filters and press
Cascade. A new cascaded filter is added to the Filter Manager.
To change the name of a stored filter, press Rename. The Rename filter
dialog box is displayed.
To remove a stored filter from the Filter Manager, press Delete.
To export one or more filters to FVTool, highlight the filter(s) and press
FVTool.
13-37
13
13-38
The imported filter can be in any of the representations listed in the Filter
Structure pull-down menu. You can import a filter as second-order sections
by selecting the check box.
Specify the filter coefficients in Numerator and Denominator, either
by entering them explicitly or by referring to variables in the MATLAB
workspace.
Select the frequency units from the following options in the Units menu, and
for any frequency unit other than Normalized, specify the value or MATLAB
workspace variable of the sampling frequency in the Fs field.
To import the filter, click the Import Filter button. The display region is
automatically updated when the new filter has been imported.
You can edit the imported filter using the Pole/Zero Editor panel.
13-39
13
Filter Structures
The available filter structures are:
Direct Form, which includes direct-form I, direct-form II, direct-form I
transposed, direct-form II transposed, and direct-form FIR
Lattice, which includes lattice allpass, lattice MA min phase, lattice MA
max phase, and lattice ARMA
Discretetime Filter (dfilt object)
The structure that you choose determines the type of coefficients that you
need to specify in the text fields to the right.
Direct-form
For direct-form I, direct-form II, direct-form I transposed, and direct-form II
transposed, specify the filter by its transfer function representation
H ( z)
The Numerator field specifies a variable name or value for the numerator
coefficient vector b, which contains m+1 coefficients in descending powers
of z.
The Denominator field specifies a variable name or value for the
denominator coefficient vector a, which contains n+1 coefficients in
descending powers of z. For FIR filters, the Denominator is 1.
Filters in transfer function form can be produced by all of the Signal
Processing Toolbox filter design functions (such as fir1, fir2, firpm, butter,
yulewalk). See Transfer Function for more information.
Importing as second-order sections. For all direct-form structures,
except direct-form FIR, you can import the filter in its second-order section
representation:
13-40
H ( z) G
b0 k b1k z1 b2k z2
k1 a0 k
a1k z1 a2k z2
The Gain field specifies a variable name or a value for the gain G, and the
SOS Matrix field specifies a variable name or a value for the L-by-6 SOS
matrix
b01
b02
SOS
b
0L
b11
b12
b21
b22
b1 L
b2 L
1
1
a11
a12
1 a1 L
a22
a22
a2 L
whose rows contain the numerator and denominator coefficients bik and aik
of the second-order sections of H(z).
Filters in second-order section form can be produced by functions such as
tf2sos, zp2sos, ss2sos, and sosfilt. See Second-Order Sections (SOS)
for more information.
Lattice
For lattice allpass, lattice minimum and maximum phase, and lattice ARMA
filters, specify the filter by its lattice representation:
For lattice allpass, the Lattice coeff field specifies the lattice (reflection)
coefficients, k(1) to k(N), where N is the filter order.
For lattice MA (minimum or maximum phase), the Lattice coeff field
specifies the lattice (reflection) coefficients, k(1) to k(N), where N is the
filter order.
For lattice ARMA, the Lattice coeff field specifies the lattice (reflection)
coefficients, k(1) to k(N), and the Ladder coeff field specifies the ladder
coefficients, v(1) to v(N+1), where N is the filter order.
Filters in lattice form can be produced by tf2latc. See Lattice Structure
for more information.
13-41
13
13-42
14
Designing a Filter in the
Filterbuilder GUI
Filterbuilder Design Process on page 14-2
Designing a FIR Filter Using filterbuilder on page 14-11
14
Introduction to Filterbuilder
The filterbuilder function provides a graphical interface to the fdesign
object-object oriented filter design paradigm and is intended to reduce
development time during the filter design process. filterbuilder uses a
specification-centered approach to find the best algorithm for the desired
response.
Note filterbuilder requires the Signal Processing Toolbox. The
functionality of filterbuilder is greatly expanded by the DSP System
Toolbox. Many of the features described or displayed below are only available
if the DSP System Toolbox is installed. You may verify your installation by
typing ver at the command prompt.
14-2
Select a Response
When you open the filterbuilder tool by typing:
filterbuilder
14-3
14
For the initial design of your filter, you will mostly use the Main pane.
14-4
The Bandpass Design dialog box contains all the parameters you need to
determine the specifications of a bandpass filter. The parameters listed in
the Main pane depend upon the type of filter you are designing. However,
no matter what type of filter you have chosen in the Response Selection
dialog box, the filter design dialog box contains the Main, Data Types, and
Code Generation panes.
Select a Specification
To choose the specification for the bandpass filter, you can begin by selecting
an Impulse Response, Order Mode, and Filter Type in the Filter
Specifications frame of the Main Pane. You can further specify the
response of your filter by setting frequency and magnitude specifications in
the appropriate frames on the Main Pane.
Note Frequency, Magnitude, and Algorithm specifications are
interdependent and may change based upon your Filter Specifications
selections. When choosing specifications for your filter, select your Filter
Specifications first and work your way down the dialog box- this approach
ensures that the best settings for dependent specifications display as available
in the dialog box.
Select an Algorithm
The algorithms available for your filter depend upon the filter response and
design parameters you have selected in the previous steps. For example, in the
case of a bandpass filter, if the impulse response selected is IIR and the Order
Mode field is set to Minimum, the design methods available are Butterworth,
Chebyshev type I or II, or Elliptic, whereas if the Order Mode field is set
to Specify, the design method available is IIR least p-norm.
14-5
14
14-6
14-7
14
14-8
14-9
14
Tip If you have Simulink, you have the option of exporting this filter to
a Simulink block using the realizemdl command. To get help on this
command, type:
>> help realizemdl
14-10
filterbuilder
The Response Selection dialog box appears. In this dialog box, you can
select from a list of filter response types. Select Lowpass in the list box.
2 Hit the OK button. The Lowpass Design dialog box opens. Here you
can specify the writable parameters of the Lowpass filter object. The
components of the Main frame of this dialog box are described in the
section titled Lowpass Filter Design Dialog Box Main Pane. In the dialog
box, make the following changes:
Enter a Fpass value of 0.55.
Enter a Fstop value of 0.65.
14-11
14
3 Click Apply, and the following message appears at the MATLAB prompt:
14-12
You can change the design and click Apply, followed by View Filter
Response, as many times as needed until your design specifications are
met.
14-13
14
14-14
A
Bibliography
Advanced Filters on page A-2
Adaptive Filters on page A-3
Multirate Filters on page A-4
Frequency Transformations on page A-5
Fixed-Point Filters on page A-6
Bibliography
Advanced Filters
[1] Antoniou, A., Digital Filters: Analysis, Design, and Applications, Second
Edition, McGraw-Hill, Inc., 1993.
[2] Chirlian, P.M., Signals and Filters, Van Nostrand Reinhold, 1994.
[3] Fliege, N.J., Multirate Digital Signal Processing, John Wiley and Sons,
1994.
[4] Jackson, L., Digital Filtering and Signal Processing with MATLAB
Exercises, Third edition, Springer, 1995.
[5] Lapsley, P., J. Bier, A. Sholam, and E.A. Lee, DSP Processor
Fundamentals: Architectures and Features, IEEE Press, 1997.
[6] McClellan, J.H., C.S. Burrus, A.V. Oppenheim, T.W. Parks, R.W. Schafer,
and H.W. Schuessler, Computer-Based Exercises for Signal Processing Using
MATLAB 5, Prentice-Hall, 1998.
[7] Mayer-Baese, U., Digital Signal Processing with Field Programmable Gate
Arrays, Springer, 2001, refer to the BiQuad block diagram on pp. 126 and the
IIR Butterworth example on pp. 140.
[8] Moler, C., Floating points: IEEE Standard unifies arithmetic
model. Cleves Corner, The MathWorks, Inc., 1996. See
http://www.mathworks.com/company/newsletter/pdf/Fall96Cleve.pdf.
[9] Oppenheim, A.V., and R.W. Schafer, Discrete-Time Signal Processing,
Prentice-Hall, 1989.
[10] Shajaan, M., and J. Sorensen, Time-Area Efficient Multiplier-Free
Recursive Filter Architectures for FPGA Implementation, IEEE International
Conference on Acoustics, Speech, and Signal Processing, 1996, pp. 3269-3272.
A-2
Adaptive Filters
Adaptive Filters
[1] Hayes, M.H., Statistical Digital Signal Processing and Modeling, John
Wiley and Sons, 1996.
[2] Haykin, S., Adaptive Filter Theory, Third Edition, Prentice-Hall, Inc.,
1996.
A-3
Bibliography
Multirate Filters
[1] Fliege, N.J., Multirate Digital Signal Processing, John Wiley and Sons,
1994.
[2] Harris, Fredric J, Multirate Signal Processing for Communication
Systems, Prentice Hall PTR, 2004.
[3] Hogenauer, E. B., An Economical Class of Digital Filters for Decimation
and Interpolation, IEEE Transactions on Acoustics, Speech, and Signal
Processing, Vol. ASSP-29, No. 2, April 1981, pp. 155-162.
[4] Lyons, Richard G., Understanding Digital Signal Processing, Prentice
Hall PTR, 2004
[5] Mitra, S.K., Digital Signal Processing, McGraw-Hill, 1998.
[6] Orfanidis, S.J., Introduction to Signal Processing, Prentice-Hall, Inc.,
1996.
A-4
Frequency Transformations
Frequency Transformations
[1] Constantinides, A.G., Spectral Transformations for Digital Filters, IEEE
Proceedings, Vol. 117, No. 8, pp. 1585-1590, August 1970.
[2] Nowrouzian, B., and A.G. Constantinides, Prototype Reference Transfer
Function Parameters in the Discrete-Time Frequency Transformations,
Proceedings 33rd Midwest Symposium on Circuits and Systems, Calgary,
Canada, Vol. 2, pp. 1078-1082, August 1990.
[3] Feyh, G., J.C. Franchitti, and C.T. Mullis, Allpass Filter Interpolation
and Frequency Transformation Problem, Proceedings 20th Asilomar
Conference on Signals, Systems and Computers, Pacific Grove, California,
pp. 164-168, November 1986.
[4] Krukowski, A., G.D. Cain, and I. Kale, Custom Designed High-Order
Frequency Transformations for IIR Filters, 38th Midwest Symposium on
Circuits and Systems (MWSCAS95), Rio de Janeiro, Brazil, August 1995.
A-5
Bibliography
Fixed-Point Filters
[1] Jackson, L., Digital Filtering and Signal Processing with MATLAB
Exercises, Third edition, Springer, 1995, pp.373422.
[2] Dehner, G, Noise optimized IIR digital filter design: tutorial and some
new aspects, Signal Processing, Vol 83, Issue 8 (August 2003) pp.15651582.
A-6