You are on page 1of 112

Getting Started with Simulink for DSP

Modeling Simulation Implementation

Getting Started
Version 1

Contents
Introduction to MATLAB and Simulink

1
Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is Simulink? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is the DSP Blockset? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Downloading the Models in This Book . . . . . . . . . . . . . . . . . . . . What Background Do I Need? . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2 1-2 1-3 1-3 1-4 1-4 1-4

Running a Simulink Model

2
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What You Need to Use the Models in This Book . . . . . . . . . . . . Starting Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing a Blocks Parameters . . . . . . . . . . . . . . . . . . . . . . . . . Changing Simulation Parameters . . . . . . . . . . . . . . . . . . . . . . . Models with Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2 2-2 2-2 2-3 2-4 2-5 2-6 2-7

Working with Models

3
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 Copying an Existing Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 Moving and Spacing the Contents of a Model . . . . . . . . . . . . 3-4

Working with Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Detaching Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Flipping and Rotating Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . Deleting Blocks and Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-6 3-6 3-7 3-7 3-7

Connecting Blocks and Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8 Drawing a Line Between Two Blocks . . . . . . . . . . . . . . . . . . . . . 3-8 Inserting a Block into a Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9 Branch Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9 Connecting Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10 Annotations, Names and Labels . . . . . . . . . . . . . . . . . . . . . . . . 3-10 Creating Your Own Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10

Creating and Observing Signals

4
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Using the Downloaded Models . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Building Your Own Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Some Simple Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding Two Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding A Short Ramp Signal to a Constant . . . . . . . . . . . . . . . . Single-Stepping to Trace the Addition . . . . . . . . . . . . . . . . . . . . Using a Multiplexer to Devise a Better Tracer . . . . . . . . . . . . .
4-4 4-4 4-5 4-7 4-8

Creating Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10 Observing Signals with a Scope . . . . . . . . . . . . . . . . . . . . . . . 4-12 Viewing Processed Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12 Sine Waves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

ii

Conditionally Executed and Masked Subsystems

5
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Conditionally Executed Subsystems . . . . . . . . . . . . . . . . . . . . 5-4 Enabled Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4 Making a Memoryless Nonlinearity . . . . . . . . . . . . . . . . . . . . . . 5-6 Making Random Binary Pulse and Impulse Trains . . . . . . . . . . 5-7 Running a Simulation from the Command Line . . . . . . . . . . . . 5-9 Measuring Processing Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10 Triggered Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11 Masked Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13

Spectra, Noise and Interactivity

6
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 Spectra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4 Viewing Spectra in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5 Spectra of Constants and Impulses . . . . . . . . . . . . . . . . . . . . . . . 6-5 Spectrum of a Ramp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8 Effects of Additive, Interactively Controlled Noise . . . . . . . . . 6-10 Listening to Noisy Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13 Changing Parameters with AddSlider . . . . . . . . . . . . . . . . . . 6-15 Setting up Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16 Using Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20

iii

Vectors, Frames, and Multirate Processing

7
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2 Sampling in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview of Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Continuous and Discrete Blocks . . . . . . . . . . . . . . . . . . . . . . . . . Converting Continuous Signals to Discrete Signals . . . . . . . . . Broadcasting Sample Times and Probes . . . . . . . . . . . . . . . . . . Samples and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sample Vectors and Frame Vectors . . . . . . . . . . . . . . . . . . . . . Comparison of Sample-Based and Frame-Based Processing . Frame Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-4 7-4 7-5 7-6 7-9 7-11 7-11 7-15 7-17

Introduction to Multirate Processing . . . . . . . . . . . . . . . . . . 7-20 What Comes Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27

iv

Contents

1
Introduction to MATLAB and Simulink
Welcome . . . . . . . . . . . . What Is MATLAB? . . . . . . . . What Is Simulink? . . . . . . . . What Is the DSP Blockset? . . . . . Downloading the Models in This Book What Background Do I Need? . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 1-3 1-3 1-4 1-4 1-4

Introduction to MATLAB and Simulink

Welcome
Welcome to Simulink, the most widely used software package for modeling and simulating dynamical systems. This book will show you how easy it is to use Simulink and MATLAB to design digital signal processing (DSP) systems. Simulink offers a powerful, yet highly flexible tool for building models and running simulations. Using Simulink, you can create visual models, in the form of block diagrams, using simple click-and-drag mouse operations. You can then run simulations and view the results in scopes, just as you would in a laboratory. You can change simulation parameters on the fly and instantly see the new results. Once you have tried Simulink for yourself, you will realize how valuable a tool it can be for designing and testing systems, and for communicating your work to others. This chapter covers the following topics: What Is MATLAB? What Is Simulink? What Is the DSP Blockset? Downloading the Models in This Book What Background Do I Need? References

What Is MATLAB?
MATLAB is the worlds premier, high-performance language for technical computing. It integrates computation, visualization, and programming in a easy-to-use environment, in which you can describe problems and solutions in familiar mathematical notation. MATLAB, which stands for matrix laboratory, is an interactive system whose basic data elements are arrays. You can use MATLAB to solve many technical computing problems, especially those with matrix formulations, in a fraction of the time it would take to write a program in a scalar-oriented language such as C or Fortran. MATLAB also offers advanced, object-oriented software engineering features, which you can use along with simple interactive procedures from the command line.

1-2

Welcome

MATLAB has evolved over a period of years with input from many users. As a result, there is a large body of third-party and public domain software available for you to use in developing your own solutions to problems. In universities, MATLAB is the standard instructional tool for courses in mathematics, engineering and science. In industry, MATLAB is the tool of choice for enhanced productivity, research, development, and analysis.

What Is Simulink?
Simulink is a software package for modeling, simulating and analyzing dynamical systems. It supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Simulink can easily accommodate multirate systems as well. Simulink offers a friendly, graphical environment, in which you can model systems in the form of block diagrams, by simply clicking and dragging blocks into a model window. You can run a model at the push of a button and modify it easily. The graphical nature of Simulink models makes them easy for others to read and understand. Simulink has a comprehensive block library of sinks, sources, subsystems (linear, nonlinear, and time-varying), connectors, and powerful conditionally-enabled blocks. You can also customize your own blocks. You can use all the facilities of MATLAB when running Simulink. You can invoke familiar MATLAB expressions and M-file functions as temporary utilities, for instance to control display and visualization. You can even encapsulate them as blocks and place them in Simulink models. Using Simulink, you can see data displayed in scopes as the simulation unfolds. This makes tracing and debugging a model, by quick, proof-of-concept demonstrations, much faster and easier than by working directly from the command line. Outside the simulation environment, Simulink serves as the primary link for targeting to chips, boards, and co-simulation platforms by means of automatic code generation.

What Is the DSP Blockset?


The DSP Blockset is a collection of Simulink blocks specifically designed for DSP applications. It provides you with extended features and gives you the extra simulation power you need to use Simulink to model DSP systems.

1-3

Introduction to MATLAB and Simulink

Downloading the Models in This Book


The examples in this book are based on a set of Simulink models that you can run and experiment with on your own computer. While you can learn about Simulink from this book without using the models, you will gain more practical experience by actually trying them for yourself. You can download the models from The MathWorks Web site at
http://www.mathworks.com/products/dspblockset/getting_started/ index.shtml

You can also download trial versions of MATLAB, Simulink, the DSP Blockset and the Signal Processing Toolbox, if you do not already have these products see the section What You Need to Use the Models in This Book.

What Background Do I Need?


Ideally, you should know a little something about MATLAB and the easy, supportive way it leads you from elementary calculations, all the way to powerful, matrix-intensive algorithm development and execution. But if you are a newcomer to MATLAB and Simulink, just keep reading here. This book will carry you through the basics. Everything you need to know and do here is easy and fun! If you want to learn more about MATLAB and Simulink, beyond what is covered in this book, you can take a look at Getting Started with MATLAB or Using Simulink. You can read either of these on-line by selecting the Help tab in the MATLAB Command Window. These references are also available on the MathWorks Web site at http://www.mathworks.com/. The topics in this book illustrate the techniques you need to use Simulink for modeling and simulating DSP systems. If you are a DSP novice, just read on Simulink can illuminate DSP concepts in very exciting ways.

References
You can consult the following references to learn more about DSP. [1] Strum,R.D. and D.E. Kirk, First Principles of Discrete Systems and Digital Signal Processing, Reading, Mass: Addison-Wesley, 1988.

1-4

Welcome

[2] Proakis, J.G. and D.G. Manolakis, Digital Signal Processing: Principles, Algorithms and Applications, Third Edition, Upper Saddle River, N.J.: Prentice-Hall, 1996. [3] Porat, B., A Course in Digital Signal Processing, New York: Wiley, 1997. [4] McClellan, J.H., R.W. Schafer, and M.A. Yoder, DSP First, Upper Saddle River, N.J.: Prentice-Hall, 1998. [5] Mitra, S.K., Digital Signal Processing- A Computer-Based Approach , New York: McGraw-Hill,1998. [6] Oppenheim, A.V.,R.W. Schafer and J.R. Buck, Discrete-Time Signal Processing, Second Edition, Upper Saddle River, N.J.: Prentice-Hall, 1999.

1-5

Introduction to MATLAB and Simulink

1-6

2
Running a Simulink Model
Getting Started . . . . . . . . . . . . What You Need to Use the Models in This Book Starting Simulink . . . . . . . . . . . . Running a Model . . . . . . . . . . . . . Changing a Blocks Parameters . . . . . . . Changing Simulation Parameters . . . . . . Models with Audio . . . . . . . . . . . . Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2-2 2-3 2-4 2-4 2-5 2-6 2-7

Running a Simulink Model

Getting Started
This chapter gets you started with the basics of Simulink. It explains how to open and run Simulink models, and how to change parameters within a model. It also describes blocks the basic elements that make up Simulink models and libraries. This chapter covers the following topics: What You Need to Use the Models in This Book Starting Simulink Running a Model Changing a Blocks Parameters Changing Simulation Parameters Models with Audio Libraries

What You Need to Use the Models in This Book


The examples in this book correspond to a set of Simulink models. The book assumes that you have downloaded these models from the MathWorks Web site see the section Downloading the Models in This Book. However, you can still read this book to learn about Simulink, even if you have not downloaded the models. To run the models, you need to have installed these MathWorks products: MATLAB (version 5.3 or later) Simulink (version 3.0 or later) Signal Processing Toolbox (version 4.3 or later) DSP Blockset (version 3.1 or later) If you are in doubt about your software holdings or versions, start MATLAB and type ver at the command line.

Starting Simulink
Unlike MATLAB, there is no special command window for Simulink. It works in the background whenever you build and run models. Before using Simulink,

2-2

Getting Started

you must first start MATLAB. You can then load an existing Simulink model by typing its name at the MATLAB prompt. For example, type lmsdemo to bring up the model shown below.

Figure 2-1: The Model Window for lmsdemo

Notice that the model lmsdemo looks like a standard block diagram. The blocks represent various processes in the model. For example, the Signal block at the upper left is a source that generates a sine wave. The Results block is a scope, which displays the signals the model generates. The lines between blocks represent the passage of data through the model. You can find the blocks in this model in Simulink libraries (see the section Libraries).

Running a Model
You can run a model by selecting the Simulation menu at the top of the model window, and then selecting Start. Selecting Stop will end the model. If you are

2-3

Running a Simulink Model

using Windows, you can also start a model by clicking on the symbol at the top of the of the model window. The square symbol next to it stops the model. Start the model lmsdemo and observe the resulting burst of activity. Even if you dont understand exactly what is going on in the model, you can readily see the exciting dynamics of what Simulink can do for you. It provides incisive, visually compelling simulations that give a panoramic overview of all areas of processing. Using Simulink is more like working with laboratory equipment than computing. Double-click on the block, labeled Results, at the right side of the model window. A new scope appears, in which you can see multiple traces, displaying more results of the simulation. You can drag the model windows around and reposition them, in order to see them better, while the simulation continues to run.

Note If you make changes to the model, when you close it you will be prompted whether you want to save the changes. You should select No, in order to preserve the model in its original form. If you do want to save your changes, you should save the model under a different name, in a separate directory set aside for your own work. You can do this using the Save As option in the File menu.

Changing a Blocks Parameters


You can change a blocks parameters while a model is running. Start the lmsdemo model and double-click on the Signal block at the upper-left of the model window. A dialog box opens, presenting you with several parameters that control the blocks operation.

2-4

Getting Started

Figure 2-2: A Dialog Box for Setting a Blocks Parameters

Click the Amplitude parameter value, and overwrite the unity value by typing 23. Clicking the Apply button at the lower right corner of the dialog box changes the amplitude. Notice that the scope traces go off the scale. Now, restore the Amplitude value to 1 and click OK. Then stop the demo.

Changing Simulation Parameters


There are several parameters that control the overall simulation. You can view or change these by selecting the Simulation menu at the top of the model window, and then selecting Parameters, which opens a dialog window as in the figure below.

2-5

Running a Simulink Model

Figure 2-3: Changing Stop time in the Simulation Parameters Dialog Box

Change the Stop time value to 34 and select OK. Now start the model again. The simulation will stop after about a second, which is all it takes to execute 34 steps of the model. If you change the Stop time setting to inf (for infinite), the simulation will never terminate until you stop it manually. Now, close the lmsdemo model, selecting No when asked if you want to save the changes.

Models with Audio


Next, try typing dspafxf at the command line. This loads a sound effects model. Run it and navigate around the information and playback blocks. Be sure to examine the parameters under the Signal From Workspace block and the underlying Simulation Parameters. Next, load and run the model dspafxf_nt. With this model, you can hear real-time audio effects and let Simulink help you dynamically experience the nature of what DSP is all about. Close these models.

2-6

Getting Started

Type dspstfft_nt (if you are using a PC) and explore a short-term spectral experiment. If you have a sound card, you can make a CD player the default audio device and observe the spectral content of your favorite music. If you have a PC microphone, make it the default audio input device and see the sorts of displays obtained when you whistle into the microphone. Note the delayed reaction time (latency) inherent in this processing. Close this model. There are many more demo models available for you to try out. Just type demos, and scroll down to the Simulink portion of the list provided.

Libraries
Simulink libraries are collections of Simulink blocks, which you can use to create models. To see all the available libraries, select the Simulink icon at the top of the MATLAB desktop, or type simulink at the MATLAB prompt. This opens the Simulink Library Browser, which lists the libraries and their sublibraries in a tree structure, as shown below. The most important libraries for this book are the Simulink library and the DSP Blockset library.

2-7

Running a Simulink Model

Figure 2-4: The Simulink Library Browser

You can open a library to see its sublibraries by clicking on the + sign next to its name. For example, clicking on the + sign next to DSP Blockset opens several sublibraries. You can open a sublibrary, such as Filter Realizations, in the same way. Furthest to the right on the tree are the individual blocks. Clicking on the name of a library or block will display a description of it at the bottom of the Browser window. To open a library in a window, type the name of the library at the MATLAB prompt. For example, type dsplib to open the DSP Blockset library, as seen in the top window in the figure below.

2-8

Getting Started

Figure 2-5: The DSP Blockset Library and Two Sublibraries

Each of the icons in this window represents a sublibrary. Click on one of the icons, such as the one labeled Filtering and that sublibrary will appear, as seen in middle window. Click on the icon for sublibrary in this window, such as Filter Designs and it will appear, as seen in the bottom window. The contents of this library are individual blocks, which you can place in models (see Creating Your Own Models).

2-9

Running a Simulink Model

2-10

3
Working with Models
Introduction . . . . . . . . . . . . . . . . . . . . 3-2 Copying an Existing Model . . . . . . . . . . . . . 3-3

Moving and Spacing the Contents of a Model . . . . . 3-4 Working with Blocks . . Copying Blocks . . . . . Detaching Blocks . . . . . Flipping and Rotating Blocks Deleting Blocks and Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 3-6 3-7 3-7 3-8

Connecting Blocks and Lines . . Drawing a Line Between Two Blocks Inserting a Block into a Line . . . . Branch Lines . . . . . . . . . . Connecting Lines . . . . . . . . . Annotations, Names and Labels . . Creating Your Own Models . . . .

. 3-9 . 3-9 . 3-10 . 3-10 . 3-11 . 3-11 . 3-11

Working with Models

Introduction
This chapter explains how easy it is to build models in Simulink. The process is very intuitive and you can experiment with it freely. For further information, take a look at the chapter Creating a Model, in Using Simulink, Version 3. This chapter covers the following topics: Copying an Existing Model Moving and Spacing the Contents of a Model Working with Blocks Connecting Blocks and Lines Annotations, Names and Labels Creating Your Own Models

3-2

Copying an Existing Model

Copying an Existing Model


The easiest way to get started building your own model is to make a copy of an existing model and experiment with it. This way you can get the feel of configuring models. First, set your MATLAB working directory to a directory where you want to save your model files. You can do this by typing cd followed by the path to that directory, at the MATLAB prompt. Preferably, your working directory should be different from the directories containing the files that came with MATLAB. Next, bring up the lmsdemo model by typing lmsdemo at the MATLAB prompt. Immediately save this file as ch3lms.mdl in the current working directory.

3-3

Working with Models

Moving and Spacing the Contents of a Model


The ch3lms model is quite compact. If you enlarge the model window and reposition the body of the model, you can get more room to work. To move the entire model, click on Select all from the Edit menu, and then click anywhere on the model and drag it with the mouse. To get finer control over where you can move the model, use the arrow keys on your keyboard instead of the mouse. Continue moving the model until you get something appearing like the figure below.

Figure 3-1: Resized ch3lms Window Showing a Repositioned Model

Click anywhere on the blank area of the model to deselect all blocks and lines. You can select the outermost blocks with the mouse and drag them toward the

3-4

Moving and Spacing the Contents of a Model

border of the window, holding the left mouse button down while you do so, to extend the signal connection lines. Moving blocks around in this way may cause signal lines to cross or to pass through blocks. While this may make the diagram difficult to read, the model will still function properly.

3-5

Working with Models

Working with Blocks


The section explains how to manipulate and work with blocks: Copying Blocks Detaching Blocks Flipping and Rotating Blocks Deleting Blocks and Lines

Copying Blocks
You can make a copy of any block in the model by holding down the Ctrl key, selecting the block with the left mouse button, and dragging the copy to another location in the model window. You can also do this by holding down the right mouse button while dragging the block, as shown in the diagram below.

Figure 3-2: Copying a Block (Right Mouse Button Is Held Down)

3-6

Working with Blocks

Detaching Blocks
To remove a block from its position, press the Shift key, select the block with the mouse, and then drag it to a new location. This leaves a gap in the model where the block was originally. You can also copy or detach a block using the Copy or Cut options from the Edit menu. You can then click on the location in the model window where you want the block to go, and select Paste from the Edit menu.

Flipping and Rotating Blocks


Sometimes it may be convenient to flip or rotate a block, to make its input and output ports face in a new direction. To flip or rotate a block that is not connected to any lines, select the Format menu and then select Flip block or Rotate block. If the block is already connected to a line, first detach the block (see Detaching Blocks), move it away from its original position, and then flip or rotate the block. You can then return it to its original position and reconnect it (see Drawing a Line Between Two Blocks).

Deleting Blocks and Lines


You can delete a block or line by selecting it with the mouse and pressing the Delete key, or by right-clicking on the block and selecting Clear from the pop-up menu. If you change your mind, you can restore the block or line by selecting Undo Delete from the Edit menu. If you are using Windows, you can also perform these operations with the looped arrow icons at the top of the model window.

3-7

Working with Models

Connecting Blocks and Lines


This section explains how to connect blocks with lines: Drawing a Line Between Two Blocks Inserting a Block into a Line Branch Lines Connecting Lines Annotations, Names and Labels Creating Your Own Models

Drawing a Line Between Two Blocks


In general, blocks have both inputs and outputs, denoted by arrow heads at the sides of the block. Source blocks, such as Signal, have only outputs, while sink blocks, such as Freq Response, have only inputs. You can connect two blocks by placing the cursor at the output of the first block, holding down the right mouse button and moving the cursor to the input of the second. This creates a line between the blocks. You should see a solid arrow at the input of the second block, indicating a good connection, as shown on the left in the figure below. If you fail to create a proper connection, you will be alerted by an open arrow, as shown on the right. Data will not pass through the broken connection.

Figure 3-3: Correct and Incorrect Connections

3-8

Connecting Blocks and Lines

Inserting a Block into a Line


You can insert a block that has a single input and a single output between two blocks that are already connected. Simply drag the block onto the line. Simulink breaks the single line segment into two and makes the connection for you. If the middle block has more than one input or output, you must first delete the line between the two blocks that are already connected. Then place the new block between the outer blocks and connect it to the outer blocks, as described in the section Drawing a Line Between Two Blocks. You can then connect the extra ports to other blocks in the model.

Branch Lines
Often you need to create a branch line from the middle of an existing line and connect it to another block. To do this, just click on the existing line, hold down the mouse button and move the cursor. This will create a branch line leading in the direction you move the cursor. To change the direction of the branch at a right angle to the original direction, release the mouse button momentarily, click on the end of the branch, and then move the cursor in the new direction. This is shown in the diagram below. To connect the branch line to another block, make a path to the block that you want to connect to and then insert the branch line into one of the blocks input ports, as described in the section Drawing a Line Between Two Blocks.

Figure 3-4: Creating a Branch Line (Right Mouse Button is Held Down)

3-9

Working with Models

Connecting Lines
Two connect the ends of two lines, if those ends are not attached to blocks, click on the end of one line and drag it until it reaches the other line. When the two ends meet, they merge to form a single line.

Annotations, Names and Labels


You can make your model much more understandable by adding text descriptions of the blocks and lines. To add text, double-click on an empty portion of the model window with the left mouse button and type the text in the rectangle that appears. Most blocks have names displayed below the block. You can change the default name of a block to a more descriptive one by clicking on the existing text area and typing the text you prefer.

Creating Your Own Models


You can use the blocks in the Simulink libraries to build your own models. Start by typing Simulink at the MATLAB prompt, to bring up the Simulink Library Browser. To create a new model, select the File menu in the MATLAB Command Window, and then select New, and finally Model. This brings up a new empty model window. Using the mouse, you can then drag blocks from the Simulink Library Browser, or from a library window (see Libraries), directly into the model window and connect them to other blocks to build your model.

3-10

4
Creating and Observing Signals
Introduction . . . . . . . . . . . . . . . . . . . . 4-2 Using the Downloaded Models . . . . . . . . . . . . . 4-2 Building Your Own Models . . . . . . . . . . . . . . 4-2 Some Simple Examples . . . . . . . . Adding Two Constants . . . . . . . . . Adding A Short Ramp Signal to a Constant . Single-Stepping to Trace the Addition . . . Using a Multiplexer to Devise a Better Tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 4-4 4-5 4-7 4-8

Creating Subsystems . . . . . . . . . . . . . . . . 4-10 Observing Signals with a Scope . . . . . . . . . . . 4-12 Viewing Processed Signals . . . . . . . . . . . . . . . 4-12 Sine Waves . . . . . . . . . . . . . . . . . . . . . 4-13

Creating and Observing Signals

Introduction
This chapter describes how to do some simple calculations using Simulink, and how to control Simulink from the MATLAB command line. It also explains how to trace Simulinks execution step by step, so that you can test your model to make sure it is functioning correctly. Once you have learned this material, you can move confidently to tackle more challenging tasks. This chapter covers the following topics: Some Simple Examples Creating Subsystems Observing Signals with a Scope

Using the Downloaded Models


If you have downloaded the models for this book (see Downloading the Models in This Book), then as you read each example, you can run the corresponding model. Before doing so, you must first change your MATLAB working directory to the directory containing the models. You can do this by typing cd followed by the path to that directory, at the MATLAB prompt. Next, type dspstartup, to set some default parameters for the models. You can now call up any of the models by simply typing its name at the MATLAB prompt.

Building Your Own Models


If you want, you can build the models described in the examples for yourself. To do so, start by typing ch4lib at the prompt. This will bring up a special library containing the blocks that are used in the models in this chapter, as shown below.

4-2

Introduction

Figure 4-1: Library of Blocks for the Models in This Chapter

To create a model, select the File menu from the library window, then select New, and finally Model. This brings up an empty model window. You can click and drag blocks from the library into the model window. Using the diagrams in this chapter as a guide, you can then connect them to build your models, as described in the chapter Working with Models.

4-3

Creating and Observing Signals

Some Simple Examples


This section provides some simple examples of performing operations in Simulink, and controlling Simulink from the MATLAB command line. The examples are: Adding Two Constants Adding A Short Ramp Signal to a Constant Single-Stepping to Trace the Addition Using a Multiplexer to Devise a Better Tracer

Adding Two Constants


To illustrate the visual nature of Simulink, consider a very simple example: adding two numbers. To see how to add 3+2 in Simulink, bring up the model in the figure below by typing ch4_3 at the MATLAB prompt. When you click the start button, the answer 5 appears in the Display block window.

Figure 4-2: Adding Two Constants

You can change the model by replacing the value 3 by a variable number a. To do this, double-click on the upper Constant block and change the parameter Constant value 3 to a. You can set the value of a at the MATLAB prompt by typing a=17. Now click the start button and you will see this figure.

4-4

Some Simple Examples

Figure 4-3: Setting the Value of a Variable

While the Simulink model has become less explicit, relinquishing partial control to MATLAB gives you greater flexibility. In this way, you can set many different variable parameter values from the MATLAB prompt, thereby avoiding the need to open so many dialog boxes.

Adding A Short Ramp Signal to a Constant


To get a more dynamic simulation, you can modify the previous model to take in a short ramp time sequence {1,2,3,4,5} to add to your constant value 2. To create a flow of single time samples, you need to replace the Constant block with a Signal From Workspace block. Type ch4_6 at the MATLAB prompt to bring up the model in the figure below. When you run the model you get this result.

4-5

Creating and Observing Signals

Figure 4-4: Putting a Ramp Sequence in Place of One Constant

You may wonder why the Display block shows the number 2. What has happened is that the numbers 1,2,3,4,5, coming from the Signal From Workspace block, were sequentially added to the constant 2 to produce the results 3,4,5,6,7. However, the first five steps of the simulation flashed past so quickly that you never saw the results in the Display block. After sending the value 5, the Signal From Workspace block continues to send zeros for the duration of the simulation (which for this example is set to 6 in the Stop time entry of the simulation parameters dialog box). What you are seeing in the Display block is the result of adding the last 0 to 2. To actually see the results of the calculations in this example, you need a way of stepping through the simulation at your own pace.

4-6

Some Simple Examples

Single-Stepping to Trace the Addition


To take control of the Simulink execution, you can make use of a single MATLAB expression: an input statement. To do this, you need to insert a MATLAB Fcn block in your model. Type ch4_7 at the MATLAB prompt to open the model shown below.

Figure 4-5: Time Step 0 When Tracing Our Ramp Addition

When you press the start button, the model halts after a single step. Note that the Display block reads 3, the result of adding the initial 1 to the constant 2. To see why this happens, double click on the MATLAB function block to open the blocks parameter dialog box. Notice that the MATLAB function entry of the dialog box is set to
input([num2str(u) is our value; Press Enter to continue])

(To read the full entry of the dialog box, click in the MATLAB function field of the dialog box and move the cursor with the arrow keys.) This command temporarily suspends the Simulink execution after each step, and prevents it from continuing until you press the Enter key. You can confirm the display value by reading this response at the command line.
3 is our value; Press Enter to continue...

4-7

Creating and Observing Signals

You can now trace the execution of the model by repeatedly pressing the start button. Each time you do so, the model executes one more step. This way you can verify that the model is working correctly.

Using a Multiplexer to Devise a Better Tracer


One of the most rewarding things about using Simulink is how quickly you can take a simple idea and improve it. As an example, you might want to revise the previous model so that you can identify the time step at which each number in the Display block was generated. To see how to do this, type ch4_8 at the MATLAB prompt, bringing up the model in the figure below.

Figure 4-6: Time Step 0 with a Better Tracing Utility

To keep track of the time steps, you can use a Digital Clock block. You also need to convey the clocks count value into the MATLAB Fcn block. Since you are merging two inputs into the single-input MATLAB Fcn block, you need to use a Mux block as a multiplexer. The MATLAB function parameter of the MATLAB Fcn block is set to

4-8

Some Simple Examples

input([num2str(u(1)) ' is our value at time= ' Press Enter to continue...'])

num2str(u(2)) ' ;

When you start the model and step through the execution by pressing the Enter key, the lower Display block shows the time at each step. The command line output begins
3 is our value at time= 0 ; Press Enter to continue...

Now, stepping through the simulation by pressing the Enter key gives you a better understanding of what is happening in the model. You can always apply this method of tracing to display how data is moving through a model.

4-9

Creating and Observing Signals

Creating Subsystems
Having done all the work of assembling a useful tracing system, it is only natural that you would want to save and reuse this device elsewhere. Also, you may not want to see all the components of the system, if all you are interested in is the information it displays. To make it easy to reuse the tracing systems and to hide its inner workings, you can use another feature of Simulink: the subsystem hierarchy. To create a subsystem, all you have to do is enclose the region of the model diagram that you want to become a subsystem, using the mouse. Place the cursor at the upper left corner of the region, hold down the left mouse button, move the cursor to the lower right corner and release the button. This selects all the blocks within your region. Now click on Create Subsystem under the Edit menu at the top of the model window. This procedure makes it possible to convert the model in Figure 4-6 to the streamlined version in Figure 4-7 below, which you can bring up by typing ch4_9 at the MATLAB prompt. You can click on the block title Subsystem and add the word Tracer to name the block more descriptively.

Figure 4-7: The Tracer Made into a Subsystem

4-10

Creating Subsystems

To see what the tracer subsystem looks like inside, just double-click on the block, opening up a second model window for the subsystem. At time step 0, this is what you see in the new window, which appears at the right.

Figure 4-8: Viewing the Tracer Subsystem (at time step 0)

In this example, a single tracer subsystem is used to keep track of the outputs of the Sum block and the Digital Clock block. Alternatively, you could create a tracer with a single display and place two copies of it into the model, one for the output of the Sum block and the other for the output of the Digital Clock block. However, if you place more than one copy of the tracer into a model, you must press the Enter key as many times as there are copies, for every time step.

4-11

Creating and Observing Signals

Observing Signals with a Scope


This section describes how to view signals with a scope. It covers: Viewing Processed Signals Sine Waves

Viewing Processed Signals


To maximize the visual advantages of Simulink, you should view signals on scopes whenever feasible. However, unless there is some periodic pattern in the data, the transient data record has no chance of settling into a stable triggering situation something you would hope to have in many laboratory environments. One way to deal with this is to slow down the simulation enough so that you can see the transient phenomena. The following model provides an example. First, type ch4_11 at the MATLAB prompt to load the model shown below.

Figure 4-9: A Transient Signal Processing Result with a Scope (at time=18)

Next, type nsecs=0.5 at the prompt. This causes Simulink to pause every half second as the simulation progresses, so that you can see what is happening.

4-12

Observing Signals with a Scope

(You can change the value of nsecs if you find that 0.5 seconds does not slow down the action sufficiently.) The default internal scope settings have been changed to the following.
Time display span: 20 Line markers: stem (reached by checking Line properties).

When you run the simulation, you can see the incoming samples. (Contrast this with a nsecs=0 setting.) After 20 samples have gone by, the earlier history has passed, and you see a steady-state display of stems 2 units high. An alternative procedure to slowing down the simulation is to use a feedback loop to repeat the burst of data, so that you can see a stable scope trace.The model below (which you can bring up by typing ch4_12) shows how to arrange such a feedback loop.

Figure 4-10: Using a Feedback Loop to Make a Transient Signal Periodic

The loop back passes through and Integer Delay block, in which the Delay in samples parameter is set to 20. This causes the signal to be repeated every 20 time steps. Now you can view a stable picture of the modified data flow.

4-13

Creating and Observing Signals

Sine Waves
Sine waves are the principal point of departure for serious modeling or experimentation. You can generate a sine wave using the Sine Wave block, from the Sources library. To see an example, type ch4_13 at the MATLAB prompt to launch the model below.

Figure 4-11: Displaying a Sine Wave On a Scope

If you want to add another sine plot to this display on the same scope, you can use an Mux block to combine the signals, as in the following example.

4-14

Observing Signals with a Scope

Figure 4-12: Displaying Two Sine Waves On the Same Scope

Now that you have gained insight into how to perform and observe some simple calculations in Simulink, you are ready to move into the realm of modeling DSP systems.

4-15

Creating and Observing Signals

4-16

5
Conditionally Executed and Masked Subsystems
Introduction . . . . . . . . . . . . . . . . . . . . 5-2 Conditionally Executed Subsystems . . . . Enabled Subsystems . . . . . . . . . . . . Making a Memoryless Nonlinearity . . . . . . Making Random Binary Pulse and Impulse Trains Running a Simulation from the Command Line . Measuring Processing Speed . . . . . . . . . Triggered Subsystems . . . . . . . . . . . . Masked Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 5-3 5-5 5-6 5-8 5-9 5-10

. . . . . . . . . . . . . . . . 5-12

Conditionally Executed and Masked Subsystems

Introduction
This chapter covers problems of more specific interest to DSP engineers, and describes the processing power of some important types of subsystems: Conditionally Executed Subsystems Masked Subsystems If you are using the downloaded models and have exited MATLAB since reading the last chapter, change your working directory to the directory containing those models, and then type dspstartup at the MATLAB prompt. See the section Using the Downloaded Models. As before, you can build any of the models in this chapter for yourself. To do so, type ch5lib at the MATLAB prompt to bring up a special library of blocks used in these models, as shown below. You can use these blocks to build your own models. See the section Building Your Own Models.

5-2

Introduction

Figure 5-1: Library of Blocks for the Models in This Chapter

5-3

Conditionally Executed and Masked Subsystems

Conditionally Executed Subsystems


This section discusses conditionally executed subsystems. These subsystems are only executed when a specific condition holds. The section covers the following topics: Enabled Subsystems Making a Memoryless Nonlinearity Making Random Binary Pulse and Impulse Trains Running a Simulation from the Command Line Measuring Processing Speed Triggered Subsystems

Enabled Subsystems
Some of Simulinks most powerful modeling techniques come through the use of conditionally executed subsystems. In these subsystems, the value of a signal somewhere in the model can either prevent or enable operation of a portion of the model as simulation time passes by. Although such flow control is easy in most languages, it is usually done by branching on the basis of elapsed time. In MATLAB, you can easily make the content of one vector depend on the values of other vectors by using logical commands, but such conditional operations are not really a primary activity. In Simulink, on the other hand as in many hardware design situations where gating is used these kinds of operations are a natural thing to exploit. One type of conditional operation in Simulink is performed by enabled subsystems. To see an example of an enabled subsystem, type ch5_2 at the MATLAB prompt to bring up the model shown below.

5-4

Conditionally Executed Subsystems

Figure 5-2: The Tracer Made Time-Selective

You can see that the subsystem is slightly different from that of Figure 4-7. Here the digital clock is not part of the subsystem. A new feature is the Enable block at the top of the Subsystem block window. You can find this block in the Signals & Systems sublibrary of the main Simulink library. The presence of the Enable block automatically causes a special input terminal to appear at the top of the Subsystem block in the top-level model on the left. The Enable block causes the Subsystem block to execute only while the input received through this input terminal is greater than 0. There are a few more new blocks in the upper part of the top-level model: a Discrete Impulse, an Integer Delay and a Sum block. Their task is to enable the Subsystem block, so they are connected to its upper input terminal. Now running this model causes these two lines to come up in the command window:
3 is the value at time= 0 ; Press Enter to continue...

5-5

Conditionally Executed and Masked Subsystems

and then
4 is the value at time= 1 ; Press Enter to continue...

The reason why this has happened is that only at these two times do enabling impulses (values greater than zero) make their way to the enable port of the Subsystem block. If you open the Discrete Impulse dialog box and change the Delay parameter to, for example, 3, then only at times 3 and 4 does the Subsystem block become enabled.

Making a Memoryless Nonlinearity


It is often necessary to carry out instantaneous nonlinear operations, such as clipping and rectifying, on signals. For instance, this simple M-code fragment half-wave rectifies a segment of a sine wave:
k=[0:99]; x=5*sin(2*pi*k*3/100); y=zeros(size(x)); y(x>0)=x(x>0); plot(k,x);hold on;stem(k,y)

You can do the same thing in Simulink. Type ch5_3 to open the model below and then start the model.

5-6

Conditionally Executed Subsystems

Figure 5-3: Half-Wave Rectifying a Sine Wave

The internal structure of the Subsystem block here is quite simple: it is just a straight-through connection with an Enable block. Since the Subsystem block executes only when the its input is greater than zero, it passes the positive portions of the sine wave through, and outputs zero when the sine is negative. You can see the output in Figure 5-3 as the portion of the graph marked with circles. The complete sine wave is also displayed for comparison. Constructing this subsystem is easy. Just select a single component such as the buffer block - select Create subsystem from the Edit menu, and then delete the enclosed component, taking care to connect the lines across the resulting gap. Enabled subsystems like this one can be a useful modeling tool.

Making Random Binary Pulse and Impulse Trains


In studying data communication systems, you may often need to create a random-amplitude, steady repetition-rate binary data source. At its simplest, the desired waveform could be a sequence of isolated impulses with amplitudes of plus or minus one. This waveform would then feed a pulse-shaping filter to

5-7

Conditionally Executed and Masked Subsystems

form a data symbol flow. Alternatively, you could stretch all the impulses into flat-top pulses that fill up the gaps between, leading to a non-return to zero (NRZ) random binary pulse train. Using enabled subsystem ideas, you can easily realize both of these waveforms. This is shown in the model below, which you can bring up by first typing ch5_4 and then Nwidth=10 at the MATLAB prompt.

Figure 5-4: Generation of a Random Binary NRZ and an Impulse Signal

5-8

Conditionally Executed Subsystems

The two Subsystem blocks differ only in the settings on their output ports. In the Out1 block of Subsystem1, the Output when disabled parameter is set to reset, which produces the impulse train in Scope1. In Subsystem2, on the other hand, the same parameter is set to held, which produces the NRZ wave in Scope2. These examples show that enabled subsystems are both simple and flexible.

Running a Simulation from the Command Line


The latter part of the chapter Running a Simulink Model, in Using Simulink, introduces the way to run simulations and change parameters via instructions from the command line. These commands can also be put into M-files, which act as controlling macros. This allows you to set up high-integrity, repeatable experimental runs in Simulink. You can make use of this feature whenever you wish to ascertain whether or not an alternative Simulink model would run faster under different parameters. Certainly, you should expect that enabled systems can sometimes speed things up, because operations do not need to execute on each simulation clock cycle. The following examples demonstrate this. The models in Figure 5-5 and Figure 5-6 below (which you can bring up by typing ch5_5 and ch5_6, respectively) show two different modifications of the model in Figure 5-4. In Figure 5-5, the random binary impulse train has been broken out and explicitly filtered by inserting an FIR filter that has Nwidth unit values for its impulse response (by typing ones(1,Nwidth) for its Numerator parameter). In Figure 5-6, the model merely retains the NRZ output pathway that Figure 5-4 contained. Both models give the same output pulse trains. The terminator blocks are attached to suppress any Simulink warnings about unconnected output lines.

5-9

Conditionally Executed and Masked Subsystems

Figure 5-5: A Hard Way of Creating an NRZ Waveform

The figure below shows a better method for creating the same model.

Figure 5-6: The Preferred Way of Creating the Same NRZ Waveform

Measuring Processing Speed


Now, to determine the run-times of the two models, make two runs of 200,000 time steps, using the sim command, by typing in the command line

5-10

Conditionally Executed Subsystems

tic;sim('ch5_5',200000);toc

and next
tic;sim('ch5_6',200000);toc

The run times for the model in Figure 5-5 are consistently about a third longer than for the purely enabled system in Figure 5-6.

Triggered Subsystems
Triggering is a variation on the enabled subsystem theme. A subsystem is triggered if it contains a Trigger block, from the Signals & Systems library. You can see an example in the smaller window in Figure 5-7 below, which differs from the example in Figure 5-3 only by the presence of a Trigger block.

Figure 5-7: A Triggered Subsystem

The Trigger block causes the subsystem to execute when the input signal changes from negative (or zero) to positive. This makes possible many

5-11

Conditionally Executed and Masked Subsystems

extensions of what enabling alone can do. Unlike the Enable block, the Trigger block forces the subsystem to output a constant signal, equal to the last value of the input signal when the subsystem was triggered. This is why the graph marked with circles is constant on the intervals where the sine is positive. The Enable block causes the graph to be zero on the intervals where the sine is negative, just as in Figure 5-3.

5-12

Masked Subsystems

Masked Subsystems
As you have seen, subsystems are easy to see, access, and modify. This has several advantages. For one, you can communicate all necessary values into a subsystem from the MATLAB Workspace. For another, you can easily make changes to a subsystem while deciding what its precise function should be. Furthermore, you can open a subsystem at any time to see its internal elements, such as Display blocks, even while the model is running. But the ease with which you can modify a subsystem also has risks. Anyone using a model can alter a subsystems internal structure, and this might unintentionally cause the model to work improperly. Futhermore, you cannot guarantee the integrity of parameter values inside a Subsystem block. To avoid these risks, you need a more disciplined type of subsystem, called a masked subsystem. To see an example of a masked subsystem, first type Nwidth=20 and then ch5_8 at the MATLAB prompt, which opens the model seen below.

5-13

Conditionally Executed and Masked Subsystems

Figure 5-8: Aspects of a Masked Subsystem for Special Signal Generation

In the model, which appears at the upper left, the Signal Generator block is a masked subsystem. When you double-click the block, rather than seeing the components of the subsystem, you see a parameter dialog box appear, as shown at the lower left. To actually see the subsystem, you must select Look Under Mask from the Edit menu. This displays the subsystem window, as in the upper right. One purpose of masking a subsystem is to provide a layer of protection between the user and the subsystem. A masked subsystem cannot be changed as easily as an unmasked one. Masked subsystems also differ from unmasked subsystems in the way that parameters are set. For example, the Signal Generator subsystem has a

5-14

Masked Subsystems

parameter Nwidth, which the top-level model needs to get a good scope trace setting. Typing Nwidth=20 at the command line broadcasts this value to all parts of the model. On the other hand, if you type 20 in the Nwidth field in the Signal Generator block dialog box, this value would not be accessible to the MATLAB workspace or to any component except the Signal Generator block. To be precise, any parameter values set in the Signal Generator blocks parameter dialog box are known only inside the workspace for the block. This is similar to specifying the arguments of a MATLAB function, which are then known only in local workspace for the function, and not to the main MATLAB workspace. Creating a masked subsystem is simple. Start by enclosing the components and clicking Create subsystem. Now, while the resulting subsystem is still selected, return to the Edit menu and select Mask subsystem. After doing this, you can no longer simply double-click on the block and see its internal structure. Instead, clicking the block opens up the blocks dialog box, just as occurs with standard library blocks. You can find details of how to arrange the parameter dialog box in the chapter Using Masks to Customize Blocks, in Using Simulink. Briefly, you select Edit Mask from the Edit menu, select the Initialization tab, as shown in Figure 5-9, and make four parameter entries, corresponding to the parameters shown in shown in the lower left pane in Figure 5-8.

5-15

Conditionally Executed and Masked Subsystems

Figure 5-9: Inside the Initialization Tab When Editing the Mask

You can change the appearance and labeling of the block with the settings under the Icon tab. Masking a subsystem is a very useful way to insulate the subsystem from the user, and to isolate parameters inside the subsystem. You can use masked subsystems to develop a more productive programming style in Simulink.

5-16

6
Spectra, Noise and Interactivity
Introduction . . . . . . . . . . . . . . . . . . . . 6-2 Spectra . . . . . . . . . . . . . . . . . . . . . . 6-4 . . . . . . . . . . . . . . . . . . . . . . . . . 6-5 6-5 6-8 6-10 6-13

Viewing Spectra in Simulink . . . . . . . Spectra of Constants and Impulses . . . . . . Spectrum of a Ramp . . . . . . . . . . . . Effects of Additive, Interactively Controlled Noise Listening to Noisy Signals . . . . . . . . . .

Changing Parameters with AddSlider . . . . . . . . 6-15 Setting up Sliders . . . . . . . . . . . . . . . . . . 6-16 Using Sliders . . . . . . . . . . . . . . . . . . . . 6-20

Spectra, Noise and Interactivity

Introduction
This chapter provides further examples of using Simulink for DSP, and shows you how to make your models more interactive. Audio signals, which capture the imagination and enthusiasm of DSP engineers, receive special attention. This chapter covers the following topics: Spectra Viewing Spectra in Simulink Changing Parameters with AddSlider If you are using the downloaded models and have exited MATLAB since reading the last chapter, change your working directory to the directory containing those models, and then type dspstartup at the MATLAB prompt. See the section Using the Downloaded Models. As before, you can build any of the models in this chapter for yourself. To do so, type ch6lib at the MATLAB prompt to bring up a special library of blocks used in these models, as shown below. You can use these blocks to build your own models. See the section Building Your Own Models.

6-2

Introduction

Figure 6-1: Library of Blocks for the Models in This Chapter

6-3

Spectra, Noise and Interactivity

Spectra
The best alternative to seeing a signal is seeing its spectrum. You can often view aspects of time signals better in the frequency domain than in their original time-domain form, especially when those signals have been contaminated by noise. Suppose you have a discrete-time signal that is a time-ordered sequence. You can think of the sequence as a vector of sample values, for example, a signal vector of length N. The transformation known as the discrete Fourier transform (DFT) swaps these N time-domain values for exactly N samples of frequency-domain information, specially linked to the given time signal. These N spectral samples are equally spaced. They start at d.c. (frequency equal to zero) and proceed in steps of 1/Nth of the sampling frequency currently in use, ending up one step short of the sampling frequency. The fast Fourier transform (FFT) delivers the DFT spectral sequence. The advantage of the fast Fourier transform is that it greatly speeds up the DFT computation by exploiting symmetries. Modern DSP would not exist without this algorithm. Of course, MATLAB and Simulink contain carefully constructed FFT routines that are available to you. Spectra obtained from sampled signals are periodic, so knowledge of this limited (length N) DFT spectral segment is enough to tell you (by extension) the values of all spectral samples, for as high a frequency as you might want to investigate. In fact, the real problem comes with the close-in spectral values; those which lie between the 1/Nth DFT grid values. There is a continuum of these values, and the DFT has no way of homing in on them apart from shrinking the grid by increasing N. Fortunately, you can avoid such extension of the time-domain vector and still home in on spectral values lying away from the DFT grid. You can access M frequency locations (always equally spaced, but this time by a 1/M grid starting at any designated frequency) in a selected span of frequencies by employing the chirp-z transform. For this, you can employ the MATLAB command czt on the N-point time-domain signal vector. You can see a nice exposition of this transform by typing cztdemo. Of course czt can be invoked to good effect in Simulink simulations through use of a MATLAB Fcn block.

6-4

Viewing Spectra in Simulink

Viewing Spectra in Simulink


This section shows how to view the spectra of signals in Simulink. It covers the following topics: Spectra of Constants and Impulses Spectrum of a Ramp Effects of Additive, Interactively Controlled Noise Listening to Noisy Signals

Spectra of Constants and Impulses


So far, only a limited collection of signal types has been discussed: constants, impulses, short ramps, sine waves, rectified sine waves, and random-amplitude impulse and pulse trains. But even this limited list affords you a chance to see some interesting variation in spectra. Since narrow-duration signals have widely spread spectra, while long-duration signals often have spectra compressed to narrow bandwidths, you can see these two extreme situations merely by examining the first two signals in the list. Type ch6_2 at the MATLAB prompt to bring up the model shown below.

6-5

Spectra, Noise and Interactivity

Figure 6-2: The Constant 2.1 and Its Spectrum

Notice that the widest thing possible (a constant) has been transformed to the narrowest thing possible: a single spectral impulse, which appears in the lower right pane. This d.c impulse, located at frequency zero, is the product of the constant and the N value (which must be a power of 2 in Simulink). The d.c. value appears in the middle of the display due to the way the FFT reorders the spectral values. This d.c.-centered ordering appears in all the spectral displays in this chapter.

6-6

Viewing Spectra in Simulink

Next, type ch6_3 at the MATLAB prompt to bring up the model in the figure below.

Figure 6-3: An Impulse of Amplitude 2.1 and Its Spectrum

As you can see, the two depictions in Figure 6-2 and Figure 6-3 have been interchanged. This time, the narrowest possible signal has been transformed to the widest possible spectrum. Any other examples you see will lie somewhere between these extremes, in both domains. Of course, in this example you cannot see anything special happening in the frequency domain due to the fftshift reordering.

6-7

Spectra, Noise and Interactivity

Notice that, in order to present the FFT block repetitively with a steady array of data with one nonzero impulse, it is necessary to make the impulse periodic, as illustrated in Figure 4-10. A viable alternative would have been to do away with the feedback loop in Figure 6-3 and terminate the simulation at the 16th time instant.

Spectrum of a Ramp
You can also spread out the single input impulse to a 5-duration ramp (but made periodic, just as in Figure 4-10). Notice that the odd point out is the value 3 with spectral index 0. This is the Nyquist frequency value of the spectrum.

6-8

Viewing Spectra in Simulink

Figure 6-4: The Ramp and Its Spectrum

Note that what you are seeing in the User-defined Frame Scope is not the complex-valued spectra, but the absolute value of the spectra. The is accomplished by inserting an absolute value block in all of the models. If you wanted to extract real and/or imaginary components, or perhaps phase information, it would be a simple matter of inserting blocks to disclose that information. Returning to the more familiar ground of sine waves, type ch6_5 at the prompt to open the model in the figure below. Observe the spectral effects (creation of

6-9

Spectra, Noise and Interactivity

harmonics) of half-wave rectification: d.c. has been generated, the tone content has been cut down to about half its original magnitude, and a large third harmonic component has been generated.

Figure 6-5: A Sine Wave and Its Spectrum with a Half-Wave Rectified Sine Wave Exhibiting Spectral Harmonics

Effects of Additive, Interactively Controlled Noise


Type ch6_5 at the MATLAB prompt to open the model in the figure below, in which you can add noise to a low frequency sine wave. To control the noise contribution, use the Slider Gain block (from the Math sublibrary). You can do

6-10

Viewing Spectra in Simulink

this interactively, while the simulation proceeds. Initially, the gain is set so low that no noise is present, as you can see in the lower left pane.

Figure 6-6: Before Adding Noise

Note that a clean, noiseless sine wave has produced a spectrum that clusters near the frequency of the sine (at around +/- 4 spectral samples away from the d.c. location). But, as expected from signal theory, you do not observe a pure spectral impulse such as you saw back in Figure 6-2. This is due to the fact that the signal generators frequency of 4.5/128 fails to fall directly onto any of the

6-11

Spectra, Noise and Interactivity

128 DFT grid points set up for the spectral analysis. So you see what is called the leakage effect. To add noise to the model, double click on the Slider Gain block to open the dialog box. Then click on the button at the top of the dialog box and move the mouse to the right, while pressing the left mouse button. You can observe the added noise in the lower left pane of the figure below. Generally, the noise has a much greater effect in the time-domain depiction. As you can see in the lower left pane of the figure below, the sine wave has been almost completely obscured by the surrounding noise. The spectrum, on the other hand, still shows high concentrations at the same values as in Figure 6-6, as you can readily see in the lower right pane of the figure.

6-12

Viewing Spectra in Simulink

Figure 6-7: Heavy Noise Added

Listening to Noisy Signals


You can listen to the noisy sine wave experiment, using a To Wave Device block from the DSP Sinks sublibrary. Type ch6_8 at the MATLAB prompt to open the model in the figure below. Now you can run the model, change slider gain and after a brief delay hear the noisy signal you are seeing on the scope and spectrum analyzer.

6-13

Spectra, Noise and Interactivity

Figure 6-8: A Noisy Sine Wave

6-14

Changing Parameters with AddSlider

Changing Parameters with AddSlider


When running a model, you might want to be able to change other block parameters using the mouse, as you did with the Slider Gain block in the model in Figure 6-7. For example, you might want to change the frequency of a sine wave. Fortunately, there is a new web-downloadable block, called AddSlider, which enables you to do this. With AddSlider, you can create special sliding buttons, called sliders, which you can click and drag with the mouse to control block parameters. You can download AddSlider along with the other models in this book - see the section Downloading the Models in This Book. To use AddSlider, add the directory containing the downloaded models to your MATLAB path. You can do this by typing addpath followed by the path to that directory, at the MATLAB prompt. This section covers the following topics: Setting up Sliders Using Sliders

6-15

Spectra, Noise and Interactivity

Setting up Sliders
To see an example of how to set up and use sliders, first type ch6_9 to open the model in the figure below.

Figure 6-9: A Noisy Two-Tone System

Suppose you want to experiment with the model by changing the frequencies and phases of the two independent sine waves, or the noise level. You might also want to change the Buffer size parameter of the Buffer block. To open each dialog box every time you want to make changes would be very cumbersome. It is much easier to set up sliders for the parameters. To set up sliders, simply type addslider at the MATLAB prompt, which brings up a library containing just the AddSlider block, as seen below.

6-16

Changing Parameters with AddSlider

Figure 6-10: AddSlider Library

You can then drag this block into the model window using the mouse, as shown in Figure 6-12. Double-click on the AddSlider block, to open the dialog box below.

Figure 6-11: AddSlider Dialog Box

At the left is a list of blocks in the model for which you can create sliders. For example, to create a slider for the Frequency parameter of the Sine Wave1 block, simply highlight Sine Wave1 in the list, check the box next to Frequency on the right, and then press Build slider. A slider dialog box labelled Sine Wave1 then appears, as shown below the model window in Figure 6-12.

6-17

Spectra, Noise and Interactivity

You can set up sliders for the parameters in any of the other blocks in the list. As an illustration, the figure below also shows a slider for the Buffer size parameter of the Buffer block.

6-18

Changing Parameters with AddSlider

Figure 6-12: Model with Two Sliders

6-19

Spectra, Noise and Interactivity

Using Sliders
You can use the slider to change the Frequency parameter of the Sine Wave1 block, even while the model is running. To do this, click on the button at the top of the slider dialog box and move the mouse to the left or right, while pressing the mouse key. Moving the button to the left lowers the frequency, while moving it the right raises the frequency. If you do this while the model is running, you can hear the results after a brief delay.

Note For some blocks, it is necessary to check the box on the slider next to Force Simulink to update model, in order to update the parameter value in the model.

If you are unable to set the frequency to exactly the value you want using the slider button, you can type in the value in the Frequency field of the slider dialog box. Then press Enter on the keyboard to update the frequency in the model. There are two fields on either side of the Frequency field labeled Min and Max, which set the lower and upper limits of the slider. The default value for Min is usually 0, and the default value of Max is usually twice the frequency value set when you create the slider. You can change the Min and Max settings by typing in new values in the fields and pressing the Enter key. It is easy to discard the sliders you have built. Simply double-click on the AddSlider block to bring up the dialog box, and press Remove all sliders. This returns the model its original state. To discard an individual slider, first bring up the slider, if it is not already open, by double-clicking on the block in the model window corresponding to the slider. (Alternatively, you can highlight the name of the block in the AddSlider dialog box and press Open block slider.) Then press Remove slider in the slider dialog box. Once you have created a slider for a block, you can still open the blocks parameter dialog box by pressing the Open block dialog button on the slider. This allows you to see all the current parameter values for that blocks parameter values. This is useful to determine the values of parameters for which you have not created sliders.

6-20

Changing Parameters with AddSlider

Note If you change a parameter in a blocks parameter dialog box, the new value of the parameter will not be updated in the slider dialog box. This can lead to a mismatch between the value displayed in the slider dialog box and the actual value of the parameter in the model.

You can save blocks fitted with sliders, if you want to build up your own library of blocks with sliders. To do this, create a new library by selecting the File menu in the model window, then New, and then Library. Then copy the block you want to save, by selecting it with the mouse and then selecting Copy from the Edit menu. Finally, click on the new model window and select Paste from the librarys Edit menu. Using blocks with sliders can make your models more interactive and flexible, which means you can maximize the fun of using Simulink.

6-21

Spectra, Noise and Interactivity

6-22

7
Vectors, Frames, and Multirate Processing
Introduction . . . . . . . . . . . . . . . . . . . . 7-2 Sampling in Simulink . . . . . . . . . . . Overview of Sampling . . . . . . . . . . . . Continuous and Discrete Blocks . . . . . . . Converting Continuous Signals to Discrete Signals Broadcasting Sample Times and Probes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4 7-4 7-5 7-6 7-9 7-11 7-11 7-15 7-17

Samples and Frames . . . . . . . . . . . . . . . Sample Vectors and Frame Vectors . . . . . . . . . . Comparison of Sample-Based and Frame-Based Processing Frame Matrices . . . . . . . . . . . . . . . . . . Introduction to Multirate Processing

. . . . . . . . 7-20

What Comes Next . . . . . . . . . . . . . . . . . . 7-27

Vectors, Frames, and Multirate Processing

Introduction
This chapter describes the unique way Simulink propagates sample timing and explains how frame-based processing can speed up simulations. This prepares the way for multirate processing, which is of crucial importance in modern DSP systems and which is especially easy to perform in the Simulink environment. This chapter covers the following topics: Sampling in Simulink Samples and Frames Introduction to Multirate Processing What Comes Next If you are using the downloaded models and have exited MATLAB since reading the last chapter, change your working directory to the directory containing those models, and then type dspstartup at the MATLAB prompt. See the section Using the Downloaded Models. As before, you can build any of the models in this chapter for yourself. To do so, type ch7lib at the MATLAB prompt to bring up a special library of blocks used in these models, as shown below. You can use these blocks to build your own models. See the section Building Your Own Models.

7-2

Introduction

Figure 7-1: Library of Blocks for the Models in This Chapter

7-3

Vectors, Frames, and Multirate Processing

Sampling in Simulink
This section presents a general discussion of sampling in Simulink, and gives some specific examples. Overview of Sampling Continuous and Discrete Blocks Converting Continuous Signals to Discrete Signals Broadcasting Sample Times and Probes

Overview of Sampling
Most people coming to Simulink from a DSP background underestimate the richness and diversity of Simulinks signal sampling capability. As a result, they may become confused by the sampling options in Simulink. DSP engineers usually perceive sampling as a nonissue in software routines (outside Simulink) that implement techniques, such as difference equations and transforms, or even do-it-yourself simulation environments. In keeping with most DSP literature, simulation time in these routines moves along in equally spaced increments. The engineer sets the time step, in order to calibrate time-domain and frequency-domain plots correctly, but views this as a minor detail. Standard DSP convention largely ignores the sample interval (or sample time), Ts, and even suppresses it from the indexing notation. Likewise, it is customary to express frequency in normalized terms. The standard approach treats clocking as a separable technology implementation issue (at least until multirate processing comes into the picture), and not really integral to the theory or the simulation methodology. But the situation with Simulink an environment originally developed for continuous-time control system modeling is more complex. This is evident from the variety of options in the Simulation Parameters dialog box, and from the wealth of terms, like solvers, you can find in the Simulink documentation. Simulink is very versatile, permitting continuous-time and discrete-time (multirate, if desired) simulation, and even hybrid continuous/discrete simulation running in the same model. Simulinks main departure from normal DSP expectations is that it does not have a central underlying clock rate that reaches up into each Simulink block and dictates behavior. Sampling should be thought of not as a feature of the

7-4

Sampling in Simulink

model as a whole, but rather of its blocks. In particular, source blocks set the sampling mode and most other blocks inherit sampling from the blocks that lead directly into them. This novel distributed sampling propagation approach takes some getting used to, but pays big flexibility dividends.

Continuous and Discrete Blocks


You can find a lot written on sampling in Simulink. The chapters Running a Simulation and Additional Topics, in Using Simulink, go into this issue in great depth, as does the DSP Blockset Users Guide, and every new user should study those explanations carefully. The intention here is only to paraphrase those discussions and to try to highlight some of the implications for DSP users. In general, there are two types of Simulink blocks: continuous and discrete. The Sine Wave block from the Sources sublibrary of the main Simulink library is a continuous source. Its icon shows a smooth sine wave. On the other hand, the block with the same name in the DSP Sources library is a discrete source. Its icon has flat spots, suggesting continuous zero-order holding of samples of a sine wave. This is no graphics aberration; it rightly conveys the full continuous-time viewpoint permeating Simulink. In the figure below, these two blocks are run together. To open the model, type
ch7_2 at the MATLAB prompt. The stemplot scope trace, at the lower left of

Figure 7-2, should be familiar to you. In DSP practice, you would not expect to have any data between sample points. If you are concerned with how the waveform would appear after passing through a D/A converter and an analog reconstruction filter, you would not necessarily expect that style of lowpass filtering to coincide with zero-order holding. The traces in the right-hand scope reveal how Simulink treats both signal sources. It renders the continuous-time sine wave as a smooth curve, but insists on assigning continuous-time values between the samples on the discrete sine wave. Moreover, it declares that zero-order holding is the processing that has yielded that continuum of values.

7-5

Vectors, Frames, and Multirate Processing

Figure 7-2: Modeling a Continuous and a Discrete Sine Wave

This simple example does much to explain why DSP users are often surprised when first using Simulink. In Simulink, the continuous-time viewpoint must prevail. If there is mixed signal handling, then implicit D/A conversion plus reconstruction filtering must take place in order for there to be linkups possible to the world outside DSP.

Converting Continuous Signals to Discrete Signals


Next, note that there are many signal sources available in the main Simulink library. Is there a way to do just the reverse of what you have seen, and make these into usable DSP sources? In other words, is there an A/D operation that you can employ?

7-6

Sampling in Simulink

The answer is yes, by inserting a Zero-Order Hold block, which resides in the Discrete sublibrary of the Simulink library. This block samples the continuous sine wave and yields a discrete-time signal. You can see this in Figure 7.3, in which both sine waves are now discrete.

Figure 7-3: Two Discrete-Time Sine Waves

However, if you use discrete sampling in two parts of a model and the sampling rates differ, the sampling rates must have integer ratio relationships. This figure shows the error message that results from having an irrational ratio.

7-7

Vectors, Frames, and Multirate Processing

Figure 7-4: Two Sine Waves with Incommensurate Sampling Rates

You can avoid this error by making sure that the sampling frequencies are related by an integer ratio. The Zero-Order Hold block provides a useful way to convert continuous signals into discrete ones. For example, the model in Figure 7-5 below is a version of the model in Figure 6-2, but uses the combination of a Constant block and a Zero-Order Hold block in place of the Discrete Constant block in Figure 6-2. The Zero-Order Hold block is necessary to convert the continuous output of the Constant block into a discrete signal. Without it, you would receive an error message from the Buffer block, which expects a discrete input.

7-8

Sampling in Simulink

Figure 7-5: Making a Constant Start Clocking

Broadcasting Sample Times and Probes


There is a way to force Simulink to comply with the DSP engineers prejudice in favor of an underlying master clock. You can broadcast a uniform sample time, which applies throughout the model, from the command line. To do this, you must make sure that every Sample time dialog entry in your system is set to receive the same variable name before defining that variables value in the command line and attempting to run the model. For example, in the model below, the Sample time parameter in the Signal From Workspace and Sine Wave blocks is set to 1/sample_freq. Before running the model, you must enter a value for sample_freq at the command line. To open the model, first type ch7_6 at the MATLAB prompt, and then type sample_freq=4.

7-9

Vectors, Frames, and Multirate Processing

Figure 7-6: Broadcasting and Measuring Sample Times with Probes

The new block you have not seen before is the Probe block, found in the Signals & Systems sublibrary of main Simulink library. This block can provide useful information about the signals in the model. In this example, there is one Probe block for each source. Notice the handy Ts reading from the Probe blocks, which you can activate by checking the Probe sample time check box in the blocks dialog box. The first vector entry on the Probe block is the value of the sample time. Before you run the model, this reads 0. But after running the model, it reads 0.25, the value of 1/sample_freq, which you have set throughout the model by typing sample_freq=4. The second vector entry on the Probe block is the offset in timing, which normally remains 0.

7-10

Samples and Frames

Samples and Frames


This section discusses the two ways of processing data in Simulink, sample-based and frame-based data. The section covers the following topics: Sample Vectors and Frame Vectors Comparison of Sample-Based and Frame-Based Processing Frame Matrices

Sample Vectors and Frame Vectors


Simulink can process data made up of sample vectors or frame vectors: A sample vector represents several sensor measurements taken at the same instant of time (the length of the vector being the number of measurements). A frame vector represents a sequence of individual samples, taken from a single sensor, over an interval of time. The individual samples are buffered to create the frame vector. To illustrate the difference between the two types of data, type ch7_7 at the MATLAB prompt to open the model in the figure below. The upper half of the model generates sample vectors, while the lower half generates frame vectors.

7-11

Vectors, Frames, and Multirate Processing

Figure 7-7: A Sample Vector and a Frame Vector with the Same Elements

The data source in the upper half of the model is a Constant block, which generates the vector [1 2 3 4 5] (set by the Constant value parameter of [1:5]). This is an example of a sample vector. When you run the model, the upper Display block displays this vector at each time step.

7-12

Samples and Frames

The data source in the lower half of the model is a Signal From Workspace block. It generates the same vector, [1 2 3 4 5], and then samples it at unit time intervals, to produce the data stream 1, 2, 3, 4, 5, 0, 0, 0, ... (The Signal From Workspace block outputs zeros after it reaches the end of the signal vector.) You can observe this data in the MATLAB Command Window when you run the model. The MATLAB Function block allows you to step through the execution by repeatedly pressing the Enter key (just as in the model in Figure 4-5). The Buffer block (with Buffer size set to 5)takes the scalar data from the Signal From Workspace block and converts it into vectors of length five. These are called frame vectors. The first frame vector consists of all zeros, since the Initial conditions parameter is set to 0. The Buffer block outputs this vector for the first five time steps, as you can see in the lower Display block. After five time steps, the Buffer block takes the first five samples from the Signal From Workspace block and generates the vector [1 2 3 4 5]. It then outputs this vector for the next five time steps. After this, the buffer is once again filled with zeros, and the Buffer block outputs a vector of all zeros. The lower Display block will then continue to display the vector [0 0 0 0 0] indefinitely. You should note two special features in Figure 7-7: thick lines, indicating vector data flow, and numbers on lines, which tell the vector widths. For example, the line coming out of the Signal From Workspace block is thin, showing that it carries scalar data, while the line coming out of the Buffer block is thick and labeled with a 5, showing that it carries vectors of length 5. You can display this information by selecting Format>Wide Vector Lines and Format>Vector Line Widths, respectively, from the model menu bar. While you can also display this information using the Probe and Width blocks, as you can see in this model, it is usually easier to use the Format menu. Next, you can see how sample vectors and frame vectors might be constructed. Notice that careful interpretation of the scope settings and displays is necessary. The whole issue of buffering is also an intricate one, offering many ways (particularly when buffer overlapping is employed) to create highly effective processing innovations. This DSP Blockset Users Guide covers this topic extensively.

7-13

Vectors, Frames, and Multirate Processing

Figure 7-8: Creating a Sample Vector and a Frame Vector

The above model is worth bearing in mind for this simplified interpretation of the two types of vectors: Mux blocks are used for combining multiple channels of data to create sample vectors. Buffer blocks are used for packaging a single channels data to create frame vectors.

7-14

Samples and Frames

Comparison of Sample-Based and Frame-Based Processing


Data processing can be either sample-based or frame-based. The simpler (and more common) option is sample-based processing, in which individual signal samples are processed one at a time. In frame-based processing, data is first buffered to form frames, which are then processed. Frame vectors are an extremely important aid to accelerated processing. Most DSP Blockset blocks can accept inbound frame vectors and perform frame-based operations. Frame-based processing can often speed up a simulation dramatically, and is recommended whenever feasible. Consider the two alternative filtering models in Figure 7-9 below. You can open the models by first typing Nwidth=20, and then ch7_9a and ch7_9b, at the MATLAB prompt. The upper model does sample-based processing, while the lower one does frame-based processing. In the lower model, the very long filter impulse response coupled with the short buffering means that buffer loads of output data undergo endpoint transient effects, which Simulink must account for. Despite this, after 1000 samples, the frame-based output snapshot in the lower scope is indistinguishable from the sample-based snapshot in the upper scope plot.

7-15

Vectors, Frames, and Multirate Processing

Figure 7-9: Sample-Based and Frame-Based Filtering Give The Same Results

In order to get a feel for how much faster the execution runs under frame-based processing, first ascertain the execution time of the sample-based model by typing at the MATLAB prompt
tic;sim('ch6_8',50000);toc

Next, determine the execution time for the frame-based model by typing
tic;sim('ch6_9',50000);toc

You will find that frame-based processing is about 35 to 40 times faster than sample-based in this example. Frequently you will encounter similar results, with frame-based offering at least an order of magnitude speedup.

7-16

Samples and Frames

Frame Matrices
You may need to process data from multiple waveforms concurrently. This data might be generated by readings from sensors dotted about the model, producing different variable values. As an illustration, consider the simultaneous readings of signal (on axis 1), noise (on axis 3), and signal plus noise (on axis 2) seen in the figure below.

Figure 7-10: A Three-Channel Data Record

If, along the 600-sample time dimension, you use a buffer to package each section of samples of length L making up the signal waveform, you will get a flow of frame vectors. Each vector will be of length L and the flow will terminate after the 600-sample supply has been exhausted. You can then couple these three frame vector flows with a Mux block, to produce a time flow of frame matrices. Each frame matrix will be of dimension L-by-3. Frame-based processing operates nearly unchanged (as far as user setups are concerned) when you go from vector to matrix flow handling. For instance, within a filter block you would simply declare that the number of channels undergoing frame-based filtering is 3 instead of 1, for this example.

7-17

Vectors, Frames, and Multirate Processing

In Figure 7-11, 3-channel filtering is performed using frame vectors. You can compare this with Figure 7-12, in which the same data is combined into frame matrices, using an Mux block, before filtering.

Figure 7-11: Frame Vector Filtering on Three Separate Channels

7-18

Samples and Frames

Figure 7-12: Frame Matrix Filtering on Three Multiplexed Channels

As expected, you see the same filter outputs following both filtering strategies. The execution times for both models are approximately equal, but the model in Figure 7-12 has the advantage of requiring fewer filter blocks.

7-19

Vectors, Frames, and Multirate Processing

Introduction to Multirate Processing


Alignment of signals that have differing sample rates requires careful attention to detail. Fortunately, there is a way that you can keep track of sample rates. Just select the Format menu and then Sample Time Colors, and components of the model with different sample rates will have different colors. Figure 7-13 shows how two differently sampled sine waves are added. The upper Sine Wave block has a Sample time setting of 1, while the lower Sine Wave block has a setting of 2. The two signals cannot be added directly, since the Sum block requires both inputs to have the same sample rate. To handle this, either you need to create some intervening values on the signal that is sampled more slowly, or else discard values on the signal that is sampled more rapidly. For the first option, you can carry out zero-insertion interpolation using the Upsample block, from the DSP Blockset library. Notice the interestingly shaped sum sequence of these two identical-frequency sine waves.

7-20

Introduction to Multirate Processing

Figure 7-13: Adding Two Sine Waves with Different Sample Rates (by inserting zeros for alignment)

A slightly different strategy is to perform discrete zero-order holding between samples by using the Repeat block. This has been done in Figure 7-14, delivering a somewhat different sum signal. You can tell that all the lines leading into the Sum block have the same sample rates, because they are all colored red. This makes it possible to carry out the addition without getting an error message.

7-21

Vectors, Frames, and Multirate Processing

Figure 7-14: Adding Two Sine Waves with Different Sample Rates (by discrete zero-order holding)

It is not too surprising that neither of these strategies has proven very attractive. The interpolation methods used have simply been too harsh to give a very good approximation to the sum signal. You will have better luck with by throwing away samples from the rapidly sampled signal. This is shown in Figure 7.15, in which a Downsample block has been inserted. This case has led to green-colored lines feeding the sum block. This means that the model is harmonized to the slowest sample rate so that the signals can be added.

7-22

Introduction to Multirate Processing

Figure 7-15: Adding Two Sine Waves With Different Sample Rates (by discarding samples)

Since systems involving sample rate changes are time-varying, serious issues regarding the ordering of processing elements arise. You cannot generally expect (as in the case of cascaded linear time-invariant filters) commutativity to hold. This can have a big impact on implementation and on how you can rearrange the order in which subsystems appear in the model. The simplest such consideration is whether or not you can interchange the order of up-sampling and down-sampling blocks. Simulink allows a quick experimental assessment of whether up-sampling by a factor of 3 and down-sampling by 2 can be interchanged this way. You can simply hook up both orderings, as in Figure 7-16, to convince yourself that the two orders do not give the same results.

7-23

Vectors, Frames, and Multirate Processing

Figure 7-16: Non-Commutativity Demonstration When Up-Sampling by 3 in Combination with Down-Sampling by 2

Building on this, you can easily investigate another one of the cascade equivalences associated with multirate systems [5, page 668], which assure you that up-sampling and filtering are commutative. You can demonstrate that this must indeed be true, by trying simple examples like the one on the figure below.

7-24

Introduction to Multirate Processing

Figure 7-17: Assured Commutativity Demonstration When Up-Sampling by 2 and Filtering

As a final basic illustration of multirate issues, take a simple signal where you are able to do perfect signal interpolation. In Figure 7-18, a Signal From Workspace block generates a ramp signal made up of only even numbers (where a jump of two has been employed to create the signal). The display block on the left shows the up-sampled version, while the display block on the right shows the linearly interpolated result obtained when the simple triangular impulse response is loaded into the dialog box of the FIR Interpolation block. Notice that, apart from the exit transient value of 6, which the filtering causes after the desired buildup to the peak output of 12, the missing values follow the pattern of injecting the missing odd number values. Of course, the total pattern is correct (as a single-step interpolation), since interpolation yields the value 6 when the signal becomes zero.

7-25

Vectors, Frames, and Multirate Processing

Figure 7-18: Perfect Linear Interpolation of a Ramp Signal

There are many more blocks available to support multirate processing, including rate conversion and special filter banks. You have seen only the most elementary start to the important topic of multirate processing. When frame sizing and multirate matters become intertwined, there is great scope for novel processing arrangements. But the opportunities for unintended effects also escalate, so it is important to monitor the behavior of your models.

7-26

What Comes Next

What Comes Next


You have seen the basics of Simulink, and some of the features that make it different from, and a valuable complement to, other tools in the MATLAB family. Now its time to delve deeper on your own and to enjoy the unique power Simulink puts at your disposal. Have fun, and build some exciting new DSP systems.

7-27

You might also like