student manual for ece 54l signals and systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf ·...

29
Student Manual for ECE 54L Signals and Systems Version 0.1: Fall, 2005 Contributors: Dr. Leslie Collins Dr. Lisa Huettel Dr. Michael R. Gustafson II Editor: Michael R. Gustafson II c 2005, Pratt School of Engineering 1

Upload: lamanh

Post on 16-Aug-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

������������ ������������������� �! #"%$'&)(�*�+,+.-0/1(�$ 243�576�6�896;:�<#=!>�?@=!ABADC�?,=!>

Student Manual for

ECE 54LSignals and Systems

Version 0.1: Fall, 2005

Contributors:Dr. Leslie CollinsDr. Lisa Huettel

Dr. Michael R. Gustafson II

Editor:Michael R. Gustafson II

c© 2005, Pratt School of Engineering

1

Page 2: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Contents

I General Course Information 4

1 Homework Purpose and Policies 5

2 Laboratory Purpose and Policies 6

II Homework Assignments 7

Homework 1: Basic Signals and Signal Manipulation 81.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.2 Practice S&S Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Homework 2: More Signals and System Properties 102.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2 Practice S&S Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.3 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

III Laboratory Assignments 11

Laboratory 1: Digital Audio Effects 121.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Laboratory 2: Touch-Tone Phone 132.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Laboratory 3: Sampling and Aliasing 143.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Laboratory 4: Tone Recognition 154.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Laboratory 5: Voice Scrambler 165.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Laboratory 6: Secret Messages 176.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

IV Appendices 18

A Creating Functions and Scripts in MATLAB 19A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19A.2 The inline Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19A.3 Scripted Functions (The “Dot-m” Method) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2

Page 3: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

A.4 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

B Making and Printing Plots in MATLAB 23B.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23B.2 The plot Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23B.3 The subplot Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24B.4 The orient Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24B.5 The print Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25B.6 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

C Flexible Programming: Using input, sprintf, and eval 27C.1 Using Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

C.1.1 The input Command for Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27C.1.2 The sprintf Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27C.1.3 The eval Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

3

Page 4: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Part I

General Course Information

4

Page 5: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Chapter 1

Homework Purpose and Policies

Homework assignments are to be turned in at the beginning of class on the day they are due. It is unac-ceptable to either work on the assignment during class or to miss class to finish an assignment. Typically,assignments will be distributed in class on Friday (and subsequently posted on the web) and will be due oneweek later. Solutions will be posted on the course website.

You are advised to start working on your assignments as soon as they are announced. Do not wait untilthe day before they are due as you may not complete them on time. Please take advantage of office hours(both for the instructor and the TAs) if you are having difficulty (or have any questions).

You are allowed to work together on homework assignments, keeping in mind that the Duke CommunityStandard applies to all assignments. However, each student must personally work each problem, legiblywrite up his or her solutions, and submit his/her own solutions. This applies to all assignments, includingcomputer simulations (e.g., MATLAB) and projects. If you turn in homework or projects that are identicalto another students’, that does not adhere to the Duke Community Standard! Also, be very aware of thedefinition of plagiarism, as that also violates the Duke Community Standard.

Note that in general, late homework will not be accepted. If special circumstances arise which preventyou from turning your assignments in on time, please speak to the instructor prior to the due date to makealternate arrangements. Assignments turned in late without prior permission will receive no credit.

5

Page 6: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Chapter 2

Laboratory Purpose and Policies

Laboratory purpose and policy document in progress...

6

Page 7: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Part II

Homework Assignments

7

Page 8: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Homework 1: Basic Signals and SignalManipulation

1.1 Introduction

The problems this week all come from the Haykin and Van Veen and are focused on basic signal classificationand manipulation. You will be determining signal characteristics such as periodicity and energy as well asusing Matlab to better visualize and construct different signals.

1.2 Practice S&S Problems

This is a listing of the problems from the book that have solutions and are related to the problems you willturning in for credit:

(1) Problem 1.51, p. 89.

(2) Problem 1.51, pp. 89-90.

1.3 Problems

For the homework assignment, you should do the following problems from Haykin and Van Veen. Note thatany time a problem has an “x” following the problem number, there has been some way in which the problemhas been expanded or altered. Pay careful attention to these extensions and alterations when performingyour work!

(1) Problem 1.42, p. 88. Do not forget to indicate the fundamental period if you believe a signal is periodic.

(2) Problem 1.43x, p. 88. In addition to what is required by the problem, write a Matlab script that willplot one cycle (period) of the input x(t), the output y(t), the DC component of the output yDC(t)(which should be a constant, of course!), and the sinusoidal component yAC(t). Be sure to properlylabel and title your graph, including your NET ID in the title of the graph. Add a legend to clearlyindicate which curve is x(t), y(t), yDC(t), and yAC(t). Turn in a copy of your figure and a copy of yourscript. Be sure to include the community standard statement at the top of your script.

(3) Problem 1.48, p. 89.

(4) Problem 1.51x, p. 89. In this case, instead of sketching

y(t) = x(10t − 5)

instead sketch

y(t) = x(−4t + 8)

(5) Problem 1.53x, p. 89. In addition, create and save the following Matlab function that emulates g(t):

function out=MyRect(in)

out = (-1<in) & (in <1);

8

Page 9: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

then write a script that uses that function to generate and plot x(t). The skeleton for the script is givenbelow:

t=linpsace( -1 , 5 , 1000);

x = %%% your code here

plot(t, x, ’k-’)

xlabel(’t’);

ylabel(’x(t)’);

%%% enter your NET ID below

title(’Staircase Function for NET ID ’)

print -deps %%% enter your file name here

Turn in a copy of your figure and a copy of your script. Be sure to include the community standardstatement at the top of your script.

9

Page 10: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Homework 2: More Signals andSystem Properties

2.1 Introduction

The problems this week all come from the Haykin and Van Veen and are focused (topic).

2.2 Practice S&S Problems

This is a listing of the problems from the book that have solutions and are related to the problems you willturning in for credit:

(1) Problem 1.55, p. 89

(2) Problem 1.56, p. 90

(3) Problem 1.62, pp. 90-91

(4) Problem 1.64, p. 91; b, c, e, g, and j

2.3 Problems

For the homework assignment, you should do the following problems from Haykin and Van Veen. Note thatany time a problem has an “x” following the problem number, there has been some way in which the problemhas been expanded or altered. Pay careful attention to these extensions and alterations when performingyour work!

(1) Problem 1.52 a, e, and f

(2) Problem 1.54 a and b

(3) Problem 1.64 a, d, f, h, i, and k

(4) Problem 1.84

(5) Problem 1.86

10

Page 11: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Part III

Laboratory Assignments

11

Page 12: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 1: Digital Audio Effects

1.1 Introduction

Digital Audio Effects In the first project, students will investigate the concepts of signal manipulation byexploring simple digital audio effects (e.g., echo, flange, and reverberation). The mathematical manipulationsdiscussed in class will be implemented in real-time and used to process signals such as the student’s voice(via microphone input) or digital music files. The use of audio signals will provide a link between themathematical manipulations (theory) and the physical realizations (perception).

12

Page 13: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 2: Touch-Tone Phone

2.1 Introduction

In a second project, students will design and implement a dual-tone multi-frequency (DTMF) encoder/de-coder. An example of a DTMF system is a touch-tone phone: when any key on the telephone key pad ispressed, a pair of sinusoids is generated and added together, producing a ”dual tone.” Background infor-mation that describes the principles behind DTMF and the touch-tone phone system application will beprovided, both to motivate the students and to provide the parameters and constraints with which they haveto work.

13

Page 14: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 3: Sampling and Aliasing

3.1 Introduction

In this project, students will investigate the effects of aliasing that can arise when digitally processing acontinuous-time signal. They will make theoretical, visual, and aural observations that illustrate theseeffects and demonstrate how an anti-aliasing filter can be used to avoid or minimize these unwanted effects.A real-world application, such as the public telephone system, will be described to provided context andsystem design parameters.

14

Page 15: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 4: Tone Recognition

4.1 Introduction

In this project, student will use a basic RLC filter in concert with a unidirectional microphone to have theirrobot seek out a particular tone in a room with two or more single-frequency sources. The student will needto design a filter that has a wide enough bandwidth to account for the tolerance of the passive componentsthey are using while narrow enough not to ”find” other frequencies in the room. They will then attach thisto their robot and write a ”search and destroy” algorithm based on the inputs from the microphone.

15

Page 16: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 5: Voice Scrambler

5.1 Introduction

The third project is designed to illustrate the basic principles of modulation and demodulation. The lab-oratory exercise will include shifting the spectrum of a speech signal in real-time (using the principle ofmodulation) such that the message is ”scrambled” and unrecognizable. Students will then transmit thescrambled signal to a second system which will operate as a descrambler.

16

Page 17: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Laboratory 6: Secret Messages

6.1 Introduction

In this project, students will use an image processing system and correlation to identify a ”secret message”and then use a frequency-based scrambling system to encode the message and communicate it to anotherteam of students. That team will need to decode the message, which in turn will motivate their robot tocomplete a particular task. This lab will integrate the Bluetooth communications protocol and robotics skillslearned from ECE 27 with the signal processing and frequency analysis of ECE 54.

17

Page 18: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Part IV

Appendices

18

Page 19: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Appendix A

Creating Functions and Scripts inMATLAB

A.1 Introduction

The following information, some directly from MATLAB’s help function, should be helpful in writing func-tions and scripts in MATLAB. There are two main ways to make a function – using the inline commandand using a dot-m file. Which one you use depends on how often you will use the function and how difficultthe function is.

Scripts are used to save large pieces of MATLAB code so that you can go back and edit it later. Whilescripts are also placed in dot-m files, they do not accept variables nor do they return them - they simply runcode.

A.2 The inline Command

MATLAB has a command that lets you develop an analytical expression for a variable. The inline commandlets you create a function of any number of variables by giving a string containing the function followed by aseries of strings denoting the order of the input variables. This method is good for relatively simple functionsthat will not be used that often.

The syntax is to put the expression to be evaluated in single quotes, followed in order by the variablesof the function with each of these also surrounded by single quotes. For example, if you want c(a, b, θ), toreturn

a2 + b2 − 2 ∗ a ∗ b ∗ cos(θ), you could create an inline function at the command line:

>> c = inline(’sqrt(a.^2+b.^2-2*a.*b.*cos(theta))’, ’a’, ’b’, ’theta’);

You can then use that function as if it were predefined in MATLAB:

>> [x,y] = meshgrid(0:.1:2, 0:.1:2);

>> mesh(x, y, c(x, y, pi/4));

MATLAB’s help file for this command is:

INLINE Construct INLINE object.

INLINE(EXPR) constructs an inline function object from the

MATLAB expression contained in the string EXPR. The input

arguments are automatically determined by searching EXPR

for variable names (see SYMVAR). If no variable exists, ’x’

is used.

INLINE(EXPR, ARG1, ARG2, ...) constructs an inline

function whose input arguments are specified by the

strings ARG1, ARG2, ... Multicharacter symbol names may

19

Page 20: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

be used.

INLINE(EXPR, N), where N is a scalar, constructs an

inline function whose input arguments are ’x’, ’P1’,

’P2’, ..., ’PN’.

Examples:

g = inline(’t^2’)

g = inline(’sin(2*pi*f + theta)’)

g = inline(’sin(2*pi*f + theta)’, ’f’, ’theta’)

g = inline(’x^P1’, 1)

If any of the inputs to these functions is a vector, make sure to use proper vector algebra (i.e. the dottedversion of math commands). In the first example for g above, if you say

x = linspace(0,1,100);

y = g(x);

you will get an error since that g function is not built to handle vectors. You would, instead, need to defineg as:

>> g = inline(’t.^2’)

A.3 Scripted Functions (The “Dot-m” Method)

MATLAB allows you to define your own functions by putting them in text files. These text files must beaccessible to MATLAB (i.e. in the same directory as you start MATLAB) and must end in .m. The functionis called by typing its name (without the .m part).

To create a function, you will write a text file with the following format:

function [OUT1, OUT2, ...] = FNAME(IN1, IN2, ...)

BODY OF FUNCTION

where OUTn are the out variables and INn are the input variables. Somewhere in the body of the function,the values of the output variables should be set. For example, a function that returns the values of the unitstep, ramp, and quadratic given an input of t might be in a file called URQfun.m, which contains:

function [USout, URout, UQout] = URQ(TimeIn)

USout = (TimeIn>=0);

URout = TimeIn .* USout;

UQout = (TimeIn.^2) / 2 .* USout;

The function is called using its filename, which is not necessarily the same as the FNAME above. In theexample above, you can plot the unit step, ramp, and quadratic for times from -1 to 2 with 100 points usingthe following commands:

%% create a vector with 100 values evenly spaced between -1 and 2

>> t = linspace(-1, 2, 100);

%% create vectors a, b, and c which will hold the unit step, ramp, and quadratic

>> [a,b,c] = URQfun(t);

%% plot each of the three new vectors vs. time

>> plot(t,a,’b+-’,t,b,’rd-’,t,c,’gh-’);

The dot-m method is especially good for 1) functions you use often and 2) functions that are too com-plicated to put in an inline. Note that you do not have to have to receive all the outputs every time. Usingthe URQfun function above, the code below will calculate the unit step, ramp, and quadratic but will onlystore the unit step and unit ramp:

20

Page 21: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

%% create a vector with 100 values evenly spaced between -1 and 2

>> t = linspace(-1, 2, 100);

%% create vectors a and b which will hold the unit step and ramp

>> [a,b] = URQfun(t);

%% plot each of the two new vectors vs. time

>> plot(t,a,t,b);

A.4 Scripts

MATLAB is a command-line driven program, and it sequentially processes whatever is entered at the �

prompt. One problem with that is that any time you need to repeat - or edit - a command, you will haveto either re-type the entire command or copy it over. Another problem is that MATLAB does not save thecommands you type, so quitting MATLAB means losing everything.

A way around this is to put everything in a script. Scripts and functions are similar in that they areboth text files ending in .m that MATLAB can read. The main difference is that functions take inputs andreturn outputs while scripts run as if you were typing their contents directly to the command line. Scriptsare run in the same way functions are called - by typing their name at the command prompt. Once a scriptstarts to run, all the commands within it will execute until the script is over or until there is an error. Forexample, the text below might be in a file called runurq.m, which is in the same directory as the URQfun.m

function above. This script will create and plot the unit step, ramp, and quadratic. It will create a propergraph (with a legend), and save the plot to a PostScript file called URQplot.eps. Finally, it will let you viewthe plot with ggv:

%% create a vector with 100 points evenly spaced between -1 and 2

t = linspace(-1, 2, 100);

%% use the URQfun function to create unit step, ramp, and quadratic

[us, ur, uq] = URQfun(t);

%% plot the three new vectors vs. time with different line styles

plot(t,us,’-’,t,ur,’-.’,t,uq,’:’);

%% give x and y labels and a title

xlabel(’Time’);

ylabel(’Function Value’);

title(’Unit Step, Ramp, and Quadratic’);

%% create a legend, and put it in the best spot

legend(’u(t)’, ’r(t)’, ’q(t)’, 0);

%% print the plot

print -deps URQplot

%% view the plot

!ggv URQplot.eps

Once this file is in your directory, you only have to type runurq at the MATLAB command prompt todo everything described above and create the plot shown in Figure A.1.

21

Page 22: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

−1 −0.5 0 0.5 1 1.5 20

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

Time

Fun

ctio

n V

alue

Unit Step, Ramp, and Quadratic

u(t)r(t)q(t)

Figure A.1: Plot created with runurq.m

22

Page 23: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Appendix B

Making and Printing Plots inMATLAB

B.1 Introduction

The following information, most directly from MATLAB’s help function, should be helpful in making andprinting plots of functions. Note that MATLAB’s help file lists MATLAB commands in all capital letters,though the actual commands are always all lower-case.

B.2 The plot Function

The plot function is used to plot sets of data on a 2-D grid. What follows comes directly from MATLAB’shelp function.

PLOT Linear plot.

PLOT(X,Y) plots vector X versus vector Y. If X or Y is a matrix, then the vector is plottedversus the rows or columns of the matrix, whichever line up. If X is a scalar and Y is a vector,length(Y) disconnected points are plotted.

PLOT(Y) plots the columns of Y versus their index. If Y is complex, PLOT(Y) is equivalent toPLOT(real(Y),imag(Y)). In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is acharacter string made from one element from any or all the following 3 columns:

Color code Meaning Symbol code Meaning Line code Meaningy yellow . point - solidm magenta o circle : dottedc cyan x x-mark -. dashdotr red + plus – dashedg green * starb blue s squarew white d diamondk black v triangle (down)

ˆ triangle (up)< triangle (left)> triangle (right)p pentagramh hexagram

23

Page 24: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

For example, PLOT(X,Y,’c+:’) plots a cyan dotted line with a plus at each data point;PLOT(X,Y,’bd’) plots blue diamond at each data point but does not draw any line.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by the (X,Y,S) triples, wherethe X’s and Y’s are vectors or matrices and the S’s are strings.

For example, PLOT(X,Y,’y-’,X,Y,’go’) plots the data twice, with a solid yellow line interpolatinggreen circles at the data points.

The PLOT command, if no color is specified, makes automatic use of the colors specified by theaxes ColorOrder property. The default ColorOrder is listed in the table above for color systemswhere the default is yellow for one line, and for multiple lines, to cycle through the first six colorsin the table. For monochrome systems, PLOT cycles over the axes LineStyleOrder property.

PLOT returns a column vector of handles to LINE objects, one handle per line.

The X,Y pairs, or X,Y,S triples, can be followed by parameter/value pairs to specify additionalproperties of the lines.

See also SEMILOGX, SEMILOGY, LOGLOG, GRID, CLF, CLC, TITLE, XLABEL, YLABEL,AXIS, AXES, HOLD, and SUBPLOT.

B.3 The subplot Function

The subplot function is used to plot multiple plot windows within the same figure. What follows comesdirectly from MATLAB’s help function.

SUBPLOT Create axes in tiled positions.H = SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrixof small axes, selects the p-th axes for for the current plot, and returns the axis handle. The axesare counted along the top row of the Figure window, then the second row, etc. For example,

SUBPLOT(2,1,1), PLOT(income)SUBPLOT(2,1,2), PLOT(outgo)

plots income on the top half of the window and outgo on the bottom half. If the CurrentAxes isnested in a uipanel the panel is used as the parent for the subplot instead of the current figure.

SUBPLOT(m,n,p), if the axis already exists, makes it current. SUBPLOT(m,n,p,’replace’), if theaxis already exists, deletes it and creates a new axis. SUBPLOT(m,n,p,’align’) places the axesso that the plot boxes are aligned instead of preventing the labels and ticks from overlapping.SUBPLOT(m,n,P), where P is a vector, specifies an axes position that covers all the subplotpositions listed in P. SUBPLOT(H), where H is an axis handle, is another way of making an axiscurrent for subsequent plotting commands.

SUBPLOT(’position’,[left bottom width height]) creates an axis at the specified position in nor-malized coordinates (in in the range from 0.0 to 1.0).

SUBPLOT(m,n,p, PROP1, VALUE1, PROP2, VALUE2, ...) sets the specified property-valuepairs on the subplot axis. To add the subplot to a specific figure pass the figure handle as thevalue for the ’Parent’ property.

If a SUBPLOT specification causes a new axis to overlap an existing axis, the existing axis isdeleted - unless the position of the new and existing axis are identical. For example, the statementSUBPLOT(1,2,1) deletes all existing axes overlapping the left side of the Figure window andcreates a new axis on that side - unless there is an axes there with a position that exactlymatches the position of the new axes (and ’replace’ was not specified), in which case all otheroverlapping axes will be deleted and the matching axes will become the current axes.

B.4 The orient Function

The orient function is used to change how the plot is oriented on the page when printing. Note that itdoes not affect how the plot looks on the screen. Furthermore, the orient command must be used each

24

Page 25: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

time a new figure opens for that figure to have a specified orientation. What follows comes directly fromMATLAB’s help function.

ORIENT Set paper orientation for printing.ORIENT is used to set up the orientation of a Figure or Model window for printing.

ORIENT LANDSCAPE causes subsequent PRINT operations from the current Figure windowto generate output in full-page landscape orientation on the paper.

ORIENT ROTATED causes subsequent PRINT operations from the current Figure window togenerate output in full-page rotated orientation on the paper.

ORIENT PORTRAIT causes subsequent PRINT operations from the current Figure window togenerate output in portrait orientation.

ORIENT TALL causes the current Figure window to map to the whole page in portrait orientationfor subsequent PRINT operations.

ORIENT, by itself, returns a string containing the paper orientation, either PORTRAIT, LAND-SCAPE, ROTATED or TALL of the current Figure.

ORIENT(FIGHandle) or ORIENT(MODELName) returns the current orientation of the Figureor Model.

ORIENT( FIG, ORIENTATION) specifies which figure to orient and how to orient it based onthe rules given above. ORIENTATION is one of ’landscape’, ’portrait’, ’rotated’, or ’tall’.

B.5 The print Function

The print function is used to save a plot as a PostScript file. What follows comes directly from MATLAB’shelp function. Note that the entire help file is not reproduced here – only the parts that are most useful.

PRINT Print graph or SIMULINK system; or save graph to M-file.

PRINT <filename> saves the current Figure window as PostScript or a printer specific format,as specified by PRINTOPT or a command line option. If a filename is specified, the output iswritten to the designated file, overwriting it if it already exists. If the specified filename does notinclude an extension, an appropriate one is appended. If the filename is omitted, the Figure issent directly to the printer as specified in PRINTOPT or a command line option.

PRINT <filename> -f<figure handle> prints the specified Figure.

PRINT <filename> -s<system name> prints the specified SIMULINK system.

Syntax: PRINT [ -ddevice] [ -options ] <filename>

PostScript devices are: -dps - PostScript for black and white printers-dpsc - PostScript for color printers-dps2 - Level 2 PostScript for black and white printers-dpsc2 - Level 2 PostScript for color printers

-deps - Encapsulated PostScript-depsc - Encapsulated Color PostScript-deps2 - Encapsulated Level 2 PostScript-depsc2 - Encapsulated Level 2 Color PostScript

25

Page 26: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

B.6 Example

The following MATLAB code demonstrates how to fill the fourth window of a 2x3 plot figure, save the figureas a PostScript file, and print your file to one of the Hudson machines.

�x=-1:0.001:1; Create a vector of numbers between -1 and 1with 0.001 between numbers

�usf = inline(’t>=0’, ’t’); This formula for usf is one of severalways to define the unit step function

�subplot(2,3,4) Create a figure with two rows of three figures andmake subplot 4 (bottom row left) current

�plot(x, usf(x)) Plot the function usf against the vector x�axis([-1, 1, -1, 2]) Change the axes so the function

is not covered by the subplot box.The values are [xmin, xmax, ymin, ymax]

�title(’Unit Step Function’) Give the current subplot a title�xlabel(’x’) Set the x-label�ylabel(’u(x)’) Set the y-label�orient landscape Use landscape (wide) orientation�print -dps usfplot Send the current figure to a file named usfplot.ps.

Note that the ‘.ps’ is automatically added�!ggv usfplot.ps The ! character lets MATLAB act as if you

were at a regular terminal. This commandlets you view usfplot.ps using ggv.

�!lpr usfplot.ps The ! character lets MATLAB act as if youwere at a regular terminal. This commandprints usfplot.ps to the cluster printer.

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

1.5

2

x

u(x)

Unit Step Function

0 0.5 10

0.2

0.4

0.6

0.8

1

1

0 0.5 10

0.2

0.4

0.6

0.8

1

2

0 0.5 10

0.2

0.4

0.6

0.8

1

3

0 0.5 10

0.2

0.4

0.6

0.8

1

5

0 0.5 10

0.2

0.4

0.6

0.8

1

6

Figure B.1: Sample Output

26

Page 27: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

Appendix C

Flexible Programming: Using input,sprintf, and eval

C.1 Using Strings

Matlab’s ability to use strings can come in very handy when writing programs to solve engineering problems.For some assignments, you will want to use Matlab’s sprintf and eval functions along with the input

command to write code that a user can modify as it runs. This will allow you to write a single program toanalyze several parameter sets rather than having to write or copy several very similar pieces of code.

C.1.1 The input Command for Strings

As given in the Matlab help system, you can use the input command to obtain strings:

R = INPUT(’What is your name’,’s’) gives the prompt in the text

string and waits for character string input. The typed input

is not evaluated; the characters are simply returned as a

MATLAB string.

This command allows you to type any valid combination of letters, numbers, and symbols. You can thereforeuse input to to obtain titles of plots, file names, and other words which you may want to use later. In orderto have Matlab incorporate these words into commands, however, you need to learn how to use sprintf andeval.

C.1.2 The sprintf Command

The sprintf command works in nearly the same way as the fprintf command, only instead of sendingcharacters to the screen or to a file, sprintf sends them into a Matlab variable. For example, in thecode below, the input command is used to generate a string (MyName) and then the sprintf commandincorporates that string into a new string (MyGreeting):

>> MyName = input(’What is your name? ’, ’s’);

What is your name? Michael

>> MyGreeting = sprintf(’Hi - my name is %s’, MyName)

MyGreeting =

Hi - my name is Michael

You can use this technique if you want to tailor the title of a graph by using specific values for that graphin the title. For example, the code below produces the plot in Figure C.1 by using numerical inputs bothto determine the domain and function of the plot and the title of the plot. Note the use of the formattingcommands in the sprintf function to make sure the proper number of decimal places appear - this will haveto be adapted to each application.

27

Page 28: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

n = input(’Power to use: ’);

x_min = input(’Minimum value: ’);

x_max = input(’Maximum value: ’);

points = input(’Number of points : ’);

x = linspace(x_min , x_max , points);

plot(x, x.^n, ’ko -’);

xlabel(’x (units)’)

ylabel(’y (units)’)

TheTitle = ...

sprintf(’Plot of y=x^{%0.1f} from %0.1f to %0.1f’,...

n, x_min , x_max);

title(TheTitle)

print -deps PlotSample.ps

0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.80

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

x (units)

y (u

nits

)

Plot of y=x1.3 from 0.1 to 0.8

Figure C.1: Plot demonstrating strings building the title

C.1.3 The eval Command

In the above examples, strings and numbers could be used to change how particular lines of code work, butthere was no way to make major changes to the code through input commands or strings. For example,there would have been no way to ask the user what color, point style, and line style to use in the plot andhave Matlab use that input in the plot command. It would be useful if the sprintf command could beused to build an entire line of code and then somehow execute that line.

This is where the eval function comes in. The argument of the eval command is a string that Matlabexecutes as if it were typed on the command line. For example, if you were to want the user to be ableto enter two numbers and then tell Matlab what to do with those (add, subtract, etc.), you could use thefollowing code. In this case, the numbers entered were 1 and 6 and the operation was *.

28

Page 29: Student Manual for ECE 54L Signals and Systems - …people.duke.edu/~mrg/xanga/labmanual54.pdf · 2012-12-19 · Homework 1: Basic Signals and Signal Manipulation 1.1 Introduction

>> Num1 = input(’First number : ’);

First number : 1

>> Num2 = input(’Second number: ’);

Second number: 6

>> Operation = input(’Operation: ’, ’s’);

Operation: *

>> MyCommand=sprintf(’%f %s %f’,...

Num1 , Operation , Num2)

MyCommand =

1.000000 * 6.000000

>> eval(MyCommand)

ans =

6

The use of the eval command allows for much greater flexibility in Matlab programming since you canhave Matlab produce entire lines of code for you. Among the most useful places for this command is ingenerating plot names. For example, the following code can be used whenever you want to specify the nameof a plot to save during the execution of a program:

PlotTitle = input(’Plot title: ’, ’s’);

PlotCommand = sprintf(’print -deps %s’, PlotTitle)

eval(PlotCommand)

29