Professional Documents
Culture Documents
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
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
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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
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
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
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
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
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
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.
1-3
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.
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
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
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
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.
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
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.
2-4
Getting Started
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.
2-5
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.
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
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
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
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 . . . .
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
3-3
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
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
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.
3-6
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.
3-7
3-8
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
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.
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
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
4-2
Introduction
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
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
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.
4-5
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
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
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.
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
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 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.
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.
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
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
(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.
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
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.
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
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
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
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
5-3
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
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
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.
You can do the same thing in Simulink. Type ch5_3 to open the model below and then start the model.
5-6
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.
5-7
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.
5-8
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.
5-9
The figure below shows a better method for creating the same model.
Figure 5-6: The Preferred Way of Creating the Same NRZ Waveform
5-10
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.
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
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
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
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
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
6-3
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
6-5
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
Next, type ch6_3 at the MATLAB prompt to bring up the model in the figure below.
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
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
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
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
6-10
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.
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
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
6-13
6-14
6-15
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.
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
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.
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
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
6-19
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
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
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
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
7-3
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.
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
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.
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.
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
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
7-9
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
7-11
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
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
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
7-15
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
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.
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
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.
7-18
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
7-20
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
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
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
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
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
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
7-27