Você está na página 1de 45

ECE-381

Signals and Systems Laboratory

Prepared by
Prof. Cory Beard

Department of Computer Science Electrical


Engineering
School of Computing and Engineering
University of Missouri-Kansas City

ECE 381: Signals and Systems Laboratory

Synopsis
This computer lab is designed to enhance and add to the ECE 380 lecture experience. Important
concepts and topics in continuous and discrete signals and systems are explored using
MATLAB. Weekly assignments progress in parallel with the ECE 380 coverage to the extent
possible.
Prerequisites
Concurrent enrollment in ECE 380

Grading
There will be 12 graded lab assignments, all mandatory, and each carrying equal weight toward
the overall lab grade.
No make-up labs without a legitimate reason.
Letter grades will be based on the following scale:
[95-100]
[90-95]
[84-90)
[70-84)
[65-70)
[55-65)
[45-55)
[0-45)

A
AB+
B
BC
D
F

Important note: There are no group lab exercises for this course. So I expect all work you turn
in to reflect your own effort. Specifically, electronic exchange of program code or results is
strictly prohibited. University guidelines regarding academic integrity will be followed if and
when any violation is noted.
Lab
Assignments
Note that, unless otherwise is said, all references in the following, such as Problem #.# or Section
#.#, are from the ECE 380 textbook:
B. P. Lathi, Linear Systems and Signals, Oxford University Press, Second Edition, ISBN-10: 019-515833-4.

Lab Topic
0

MATLAB Tutorial Session (mandatory; not graded)

Analog Signals: Operations, periodicity, energy, and power

Complex exponentials and chirp signals (Bring headphones)

Touch-tone telephone dialing and music synthesis (Bring Headphones)

Analog system response using ODE solvers

Laplace Transforms

Filters

Introduction to Discrete Time Systems

Discrete-time system response by recursion

Discrete Time difference equation and convolution

10

Fourier Series and Fourier Transform

11

Sampling,DFT and FFT

12

UPCOMING

ECE 381: Laboratory 0


MATLAB Tutorial Session

Attendance is mandatory. There will otherwise be no grading.


This session is intended as a means for you to pick up the bare essentials of
the Matlab programming environment and language features that you will need
to carry out the assignments. Ideally, you have had prior experience with Matlab
--have taken a course on it, or used it before. If you have not, do not be
too concerned. MATLAB is not hard to learn provided, of course, you have
some programming experience and are willing to give some extra time to it.
In this session, we will go over some general features of Matlab and programming
using Matlab. The focus is placed on graphing and matrix indexing, which are
two areas where Matlab is particularly powerful.

Working with complex numbers


>> z = -3 - j*4
>> z_real = real (z)
>> z_imag = imag (z)
>> z_mag = sqrt (z_real^2 + z_imag^2)
>> z_mag = abs (z)
>> z_rad = atan2 (z_imag, z_real)
>> z_rad = angle (z)
>> z_deg = angle (z) * 180/pi

Vectors
>> a = [2 3]
>> a = [2 3];

%does not print the input

>> a = [2 3]

%transpose of the vector

>> a = [2:5]

%defines a set of values to a

>> t = 4
>> w = exp (j * (2 * pi * t))

%try with different values of t like t =


.25, .5, .75

>> t = [4:0.1:5]

%define a vector that starts with 4 and


ends in 5 with steps of .1

>> w = exp (j*(2*pi*t))

Matrix Operations

>> b = [2 3 4 ; 5 6 7]

%creates a 2 x 3 matrix. ; to separate


rows.

>> c = [8 7 6 ; 5 4 3]
>> d = b + c
>> d = [b + c]
>> d = b * c

%What happens when you try executing this

>> d = b * c
>> d = b * c
>> d = b.* c

%Element wise multiplication

>> sin (d)


Creating an executable file
First, you will need to create the file. The easiest editor on our system is
to just use the built in Matlab editor. It will allow you to do some very simple
file manipulations. Matlab executable files (called M-files) must have the
extension ".m". To run the executable file type
>> load <filename> in the command window.
To add comments use %.

Graphing
t = [1:.125:10];

w = exp (j * (2 * pi * t));
plot (real (w), imag (w));
xlabel ('Real (w)');
ylabel ('Im (w)');

Loops
1. for loop
h = 0.1;
x = [0:h:2];
y = 0*x;
y(1) = 1;
size(x)

%initialize y to 0
%display size of x

for i=2:21,
%begin with i=2 and loop till i=21
y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
end plot(x,y)
plot(x,y,'go')
plot(x,y,'go',x,y)

2. while loop
h = 0.001;
x = [0:h:2];
y = 0*x;
y(1) = 1;
i = 1;
size(x)
max(size(x))
while(i<max(size(x)))
y(i+1) = y(i) + h*(x(i)-abs(y(i)));
i = i + 1;
end
plot(x,y)
if statement
a = 4;
b = 4;
if (a<b)
y = -1;
else if (a>b)
y = 2;
else
y = 3

end

Try these problems from text.


B.2 (c,d)
B.3 (c,e,f)

ECE 381: Laboratory 1


Analog Signals: Operations, periodicity, energy, and power
Part I. Matlab notes
In the tutorial hour last week, we have covered more Matlab material than
necessary to do this assignment. In the following, we still revisit plotting
and scripts. The emphasis is on plotting and presentation features and
quality of our plots.
Plotting in Matlab is easy and straightforward. Say, we have two vectors, t
and x, holding, respectively, the sampling times and the corresponding
amplitude values for an analog signal x(t). For future reference, let us call
this "vector" or "sampled" representation of an analog signal. We can plot
x(t) versus t by entering plot(t,x) at the command prompt. We can control the
line type and color:
>> plot(t,x,'r--'); % red, dashed line
>> % Trailing portion after the first percent character of each line
>> % is deemed a comment, and ignored.
In the case we omitted the time vector, and entered just plot(x), Matlab
would supply the integer vector 1:length(x) in its place automatically, which
is generally not correct for sampled analog signals.
We can have multiple signals plotted on the same time axis, e.g., as:
>> plot(t1,x1,'-',t2,x2,'.'); % x1: solid line, x2: dotted line
Note that t1 and t2 need not be identical time vectors; in fact, they can
even be of different lengths. However, associated time and amplitude vectors,
e.g., t2 and x2, must have the same length.
Alternatively, multiple signals can be plotted on the same axis by using the
hold command. Once this command is entered, the current plot, if any, is held
in the figure window, and all subsequent plots are superimposed on it. This
behavior can be cancelled by entering hold off.
Other useful plotting utilities include axis, xlabel, ylabel, title, text,
gtext, grid and legend. Take the following examples as illustrations of their
usage. To learn more, we can use help on these commands, or on any other
Matlab command for that matter. For plotting in particular, help graph2d is
useful.
>> axis([ xmin xmax ymin ymax ]);
% to set the x- and y-axis ranges
>> axis tight;
% zoom in as much as possible without
losing any part of the plot
>> axis off;
% no axes are drawn
>> xlabel('Time t (seconds)');
>> ylabel('Amplitude x (volts)');
>> title('x_2(t) versus t');
>> text(x0,y0,'An annotation, note, etc.'); % placed at the coordinates
(x0,y0)

>> gtext('Another annotation');


%
>> grid;
%
and y-axis tick marks (toggles)
>> legend('plot 1','plot 2');
%
them as
>>
%

place it anywhere using the mouse


draw or remove grid lines at the xdraws two sample lines, and labels
'plot 1, 'plot 2'

In the above discussion and examples, we had only one graph in mind, with one
or more plot in it. When we execute a plot command, or any of the utility
commands mentioned above, this affects either the currently active "figure,"
or if there is none, one is created automatically. In Matlab, "figure" is the
window that pops up, and into which we plot data. At any point in time, the
active figure is the last figure window we had on the foreground (say, by a
mouse click on it), or the last figure window that is created. We can create
additional figure windows by entering figure at the prompt. Each figure
window thus created has an integer handle, automatically assigned by Matlab.
This information is available on the title bar of the window, e.g., "Figure
No. 2", and is also returned by the figure command. We can explicitly specify
this handle ourselves by passing it as an argument:
>> figure(5); % create new figure window with handle 5
This also provides for bringing a figure window to the foreground, and thus,
making it the currently active figure:
>> figure(5); % create new figure window with handle 5
>> figure(11); % create yet another one, which becomes active
>> figure(5); % make "Figure No. 5" active again
We can export the contents of the active figure window in different formats.
This is exemplified for the two most common formats:
>> print('-dps','filename.ps');
% black-and-white postscript
>> print('-djpeg','filename.jpeg'); % standard quality JPEG image
The files filename.* are created in the present working directory, and they
are to reflect what we see in the active figure window on the computer
screen. It is not a bad idea to view the outcome by an appropriate tool
(gsview, a browser, an image viewer, etc.) because the quality may sometimes
be low. Of course, help print tells about many other formats and
configuration options. Also check out the File menu options in the figure
window. We can export the contents via the Export option under this menu, or
send the contents directly to a printer.
Finally, as a means of organizing multiple plots in one figure window, we can
use subplots. This is like opening a clean slate into which we can plot, but
no new figure window is created. Instead, the active figure window is divided
into a two-dimensional array of separate plotting areas, or boxes, each with
its own title, x- and y-axis labels, axis range settings, annotations, etc.
Take the following example:
>> figure(2); clf;
>> subplot(2,3,1);
>>
>> plot(t1,x1);

%
%
%
%

make "Figure No. 2" active; and, clear its contents


2-by-3 array of plotting areas
the first box, box(1,1), is activated
plotted in box(1,1)

>>
>>
>>
>>
>>
>>

subplot(2,3,3); % box(1,3) is active (row 1, column 3)


plot(t3,x3);
% now box(1,3) is affected
hold on;
plot(t30,x30); % have a second plot in box(1,3)
subplot(2,3,2);
title('Nothing plotted yet'); % this is the second box, box(1,2)

So, the plotting areas are indexed in row major order, and the second row in
the 2-by-3 layout of this example has areas 4, 5, and 6 from left to right.
But, the example could continue as follows:
>> subplot(2,1,2); % layout switched to 2-by-1
>>
% second row, or box(2,1), is active
>> plot(t4,x4);
% spans the entire 2nd row
>>
% existing subplots of the 1st row unaffected
Obviously, the presentation quality of Matlab figures can be enhanced in a
lot of ways. One needs to try and experiment with ideas and available tools.
For the simple plots that we have in this assignment, above should be
sufficient.
As for Matlab scripts, called m-files, these are plain text files with the
extension ".m", e.g., "myscript.m". An m-file simply contains Matlab
statements and commands in the same way as one would enter them at the
prompt. All command-prompt rules apply. If a statement is terminated by a
semi-colon, the result is not echoed; otherwise, it is echoed. If a statement
is too long to fit on one line, escape to the next line is possible by using
an ellipsis "...". Control structures such as if-elseif-else-end, or for-end
can be used. So on, so forth. For example, all statements in the above
examples could be put in an m-file, say examp.m, and executed by entering
examp at the command prompt. Important point to note about Matlab scripts is
that they execute in the global scope. So, all variables defined in a Matlab
script are available after the completion of its execution. If such a
variable happens to already exist in the global scope, it will be overwritten
by the script's execution. For example, if examp.m contained nothing but the
example statements of this overview, then the various time and amplitude
vectors used would have to be defined in the global scope prior to executing
examp. Otherwise we would get errors. Scoped execution is possible through
the use of Matlab functions, which are again m-files with a special header,
but functions are not needed in this assignment. Still, Exercise 4 could be
done nicely by writing a function, which can be reused for similar problems
with different parameters, or even with different number of terms in the
combination.

ECE381 - SCE/UMKC/WS06

ECE 381: Laboratory 1

Fall 2015

Analog Signals: Operations, periodicity, energy, and power


Part II. Assignment

Matlab notes | Assignment

Useful signal processing routines for this assignment include inline.


1. Write a Matlab script that (a) obtains the even and odd parts of figure P1.1-2 (Figure d) of Problem 1.11 and P1.2-2 of Problem 1.2-2, and (b) plot them against the original signals in a 2-by-2 arrangement of
subplots. Each row is to depict an original signal, and its even and odd parts in that order. E.g.,
subplot(2,2,4) depicts the even part of Signal 2. Include subplot titles, or x-/y-axis labels to clearly
identify each sketch. Have your script also compute the signal energy for all four signals at hand. Verify
that these results comply with the statement that, for an energy signal, the signal energy equals the
sum of the energy in its even and odd parts. Explain discrepancies, if any.
Tip 1: For better visualization of finite-duration signals in your plots, make sure that their
sampled representation spans an interval larger than the actual signal duration.
Tip 2: Also make sure that the x-/y-axis ranges are adjusted so that the signal form is clearly
depicted (neither too small in its window, nor too large to have entire edges coincide with and
lost in the window boundary). Check out the axis routine for that.
Tip 3: You can also annotate each subplot with the signal energy. To do so, you can use the text
or gtext commands, or you can do it interactively through the Insert menu on the figure
window.
2. Let s(t) = sin(t) Use Matlab to sketch each of the following signals over the range -2 t6
using a small time step (say, 0.02 s). Have your script also compute the signal power.
(a) x(t) = u[s(t)] (b) f(t) = r[s(t)]

(c) h(t) = e

s(t)

Present your results, i.e., compose the four sketches, in a convenient manner as in Exercise 1 above.
One figure of a 2-by-2 subplot arrangement, or two figures of 2-by-1 arrangement each, it is up to you.
Likewise for titles, axes labels, annotations, etc. The same applies to Exercise 3 that follows.
3. Let x(t) = 2u(t+1) r(t + 1) + r(t 1). Use Matlab to plot the signals x(t), y(t) =
x(2t-1), and f(t) = x(1-2t). Have your script also compute the signal energy for all three. Do
the signal energies of y(t) and f(t) relate to that of x(t) as you expect? Explain discrepancies, if
any.
For each of the above exercises, turn in all Matlab scripts, plots, and explanations and comments. In this
assignment and all others, unless explicitly asked otherwise, you can include your explanations as comment
lines at the very end of your scripts. In all cases, your scripts must contain leading comment lines identifying
you and the particular assignment/exercise they are written for. Please do NOT write your student ID number
there.
School of Computing and Engineering
University of Missouri - Kansas City

Last updated: September,2015

11

ECE 381: Laboratory 2


Complex exponentials and chirp signals
Part I. MATLAB notes

Fall 2015

MATLAB has certain built-in constants such as pi ( = 3.1415) and i or j ((1)1/2). We will need these constants in this and in most of the coming
assignments. Not so much of a problem with pi, but one often uses i or j as
loop variables. Should this happen, the built-in values can be restored by
way of recomputation as sqrt(-1), or by way of removing them from the
workspace by "clear i j". Note that the latter would be the way to restore
the number pi.
Note that we don't declare variables in MATLAB. Consequently, all variables
are in general assumed to store double-precision complex values. So, we can
use the built-in constants i and j almost anywhere in our expressions and
computations. For example, 3+j*4 and 2*exp(-j*pi/4) are two complex numbers
expressed in rectangular and polar coordinate systems, respectively. Given a
complex number x, we can get its real and imaginary parts, magnitude and
phase by real(x), imag(x), abs(x), and angle(x), respectively.
We have so far learned that, to MATLAB, all variables are matrix objects, and
most operations on or between variables are matrix-algebraic ones. For
example, A*B requires the inner dimensions of A and B be identical. However,
not all computations one needs are matrix-algebraic. For example, consider
taking the weighted average of the set of numbers. contained in a row vector
named numbers. Let the weights be stored in another row vector weights of the
same size as numbers. Then, the weighted sum can be computed by element-wise
multiplication and summing as in sum(numbers.*weights). Although, in this
case, the result could be obtained matrix-algebraically by numbers*weights',
where we transposed weights making it a column vector, there are times when
an element-wise operation is inevitable. Take note of and always remember
this dot-operator method for element-wise operations. As another example,
consider squaring each and every element of a vector (or matrix for that
matter), say, x. This is accomplished by x.^2.
On the other hand, any operation that is not matrix-algebraic by definition
will be performed in an element-wise manner. Some examples are sin, cos,
real, imag, abs, and angle. Take cos(x) for example. This will return an
array (vector or matrix) the same size as x containing the cosines of the
corresponding elements of x. Similarly for the others.
We have seen MATLAB figures and plotting in the MATLAB tutorial and the
previous assignment. In addition to such visual output, MATLAB is equipped to
provide audio output as well. The command for this is sound, and we call it
by passing two arguments. The first is a vector corresponding to a sampled
audio signal. The second is the sampling frequency in Hertz (or we say,
sampling rate in samples/second). This second argument is optional, an if
omitted, it defaults to 8192 Hz. Note that knowledge of the sampling
frequency is essential in playing out the audio signal correctly as it
determines the time separation between adjacent samples, hence the duration
of the signal. One point to note is, the sample values should be in the
interval from -1 to +1, otherwise they are clipped. Other than that, this

12

command is as powerful as to play cd quality stereo music, provided that we


have the right sound card. Read the help on sound to learn more.

13

ECE381 - SCE/UMKC/WS06

ECE 381: Laboratory 2

Fall 2015

Complex exponentials and chirp signals


Part II. Note on chirp signals

MATLAB notes | Note on chirp signals | Assignment

Chirp signals, also called swept-frequency signals, are sinusoids whose frequency varies linearly with time. To
understand chirp signals, we need the concept of instantaneous frequency of a sinusoid. Consider the sinusoid
x(t) = cos[(t)] with a general argument (t). The instantaneous frequency of x(t), call it f i (t), is defined as the
derivative of (t) with respect to t, divided by 2, i.e., f i (t) = '(t)/2.
As a simple example, consider the constant-frequency sinusoid, or as we also say, the single-tone signal
x(t) = cos(2f 0 t + ). The instantaneous frequency of this signal is found as f i (t) = f 0 for all t, as we intuitively expect.
Let us now try to find the argument of a sinusoid whose instantaneous frequency varies linearly from f 0 at time t 0 to f 1
at time t 0 +T for some T > 0. That is, we want f i (t 0 ) = f 0 and f i (t 0 +T) = f 1 . First, set up the equation of the line through
these two points in the time-frequency plane as f i (t) = f 0 + (f 1 -f 0 )(t-t 0 )/T. Second, take the running integral of f i (t) up
to time t , and multiply the result by 2. Thus, we find:
(t) = 2f 0 t + (f 1 -f 0 )(t-t 0 ) 2 /T + ,
where is a phase constant.
From this general analog chirp signal, we can reach its discrete-time counterpart by way of sampling. Let S be the
sampling rate in Hertz (or, samples per second). Also let t s = 1/S be the sampling interval in seconds. Now consider
the discrete-time signal x[n] = cos([n]), where [n] = (nt s ), and (t) is as found above with t 0 = 0 and = 0 for
simplicity. We can express the resulting general discrete-time argument as
[n] = 2F0 n + (F1 -F0 )n2 /TS,
where F0 = f 0 /S and F1 = f 1 /S are the digital frequencies in cycles per sample corresponding to the analog frequencies
f 0 and f 1 , respectively. Now, assume that TS is an integer, say N. Then, we reach a general expression for a discretetime chirp signal:
x[n] = cos[2F0 n + (F1 -F0 )n2 /N], n = 0, 1, 2, , N-1.
This signal, which is defined whether or not there is an underlying analog signal being sampled, is called an N-sample
chirp signal, and its digital frequency varies linearly from F0 to F1 in the span of N samples.
We conclude this note by noting that, while analog chirp signals are never periodic, discrete-time chirp signals can be
periodic.
School of Computing and Engineering
University of Missouri - Kansas City

Last updated: September,2015

ECE381 - SCE/UMKC/WS06

ECE 381: Laboratory 2

Fall 2015

Complex exponentials and chirp signals


Part III. Assignment

MATLAB notes | Note on chirp signals | Assignment

In this assignment, the MATLAB functions you will use include real, imag, abs, angle, cos,
and sound as well as the built-in constants pi and j. You are supposed to generate the
chirp signals in Exercises 1 and 2 using standard MATLAB routines and tools.
1.

Consider the analog chirp signal x(t) = cos(1000*2t 2 ).


a. On one figure with a 3-by-1 subplot layout, plot x(t) over 0 t T for T = 2, 6,
and 10. Use a small time step, say
t = 25e-6 (sampling frequency of 40,000 Hz).
b. What do the plots reveal as T is increased? Is this signal periodic? Should it be?
c. The instantaneous frequency is the derivative of the argument for a sinusoid
divided by 2. In this case, it would be the derivative of 1000*2t 2 . How does
its instantaneous frequency vary with time?
d. Use the MATLAB sound function to listen to this chirp signal.
hear match your answer to (c)?

How does what you

2. Consider the analog chirp signal x(t) = cos[2f 0 t + (f 1 -f 0 )t 2 /T]. When this is
used, the frequency of x(t) varies linearly from f 0 to f 1 over 0 t T. Use f 0 and
f 1 as 0 and 4096 Hz, respectively, and T = 0.5 sec.. Generate the vector x corresponding
to x(t), with t = 1/8192. Play the following ten signals and listen:
1. x
5. [x x x x]
9. [x y x y]

2. y = x(length(x):-1:1)
6. [-y y -y y]
10. [[x -y]' [y -x]']

3. [x -x]
4. [y y]
7. [x y]
8. [y x]

Does what you hear make sense? How does the instantaneous frequency seem to vary for each
signal?

3.

The general solution to a second order differential equation with complex roots is a
sinusoid multiplied by an exponential of the form
x(t) = e at cos(2ft+ ). For all of the plots below, be careful to choose a range of time
axis values that displays the signal well.
a.

Plot a signal whose amplitude envelope decays by 50% every 3 seconds,


oscillates 2 times per second, and has a phase shift of 0. What are the values
for a, f, and ?
b. Plot a signal whose amplitude envelope never decays, oscillates 3 times per second,
and has a phase shift of /2.
What are the values for a, f, and ?
c. Plot a signal whose amplitude envelope doubles in size every 3 seconds,
oscillates 1 time per second, and has a phase shift of . What are the values
for a, f, and ?
d. Plot a signal whose amplitude envelope decreases to 75% of its previous value every 2
seconds, never oscillates
(i.e., the sinusoidal term is a constant), and and has a phase shift of 0. What are
the values for a, f, and ?
For each of the above exercises, turn in all MATLAB scripts or diaries, plots, and explanations
and comments.

School of Computing and Engineering


University of Missouri - Kansas City

Last updated: September, 2015

ECE 381: Laboratory 3


Touch-tone telephone dialing and music synthesis
Part I. MATLAB notes
In this assignment, you will need to use such programming constructs of
MATLAB as conditional statements, for loops, and functions.
Conditional statements: The most common way to execute alternative sets of
statements conditionally is to use if statements. Another way is to use case
statements, but this is not as versatile as the former. In other words,
anything that can be accomplished by a case can also be accomplished by an if
statement, but the converse is not true. So the following brief discussion is
on if statements only.
The general form of an if statement in MATLAB is as follows:
if Condition 1,
Statement[s]
elseif Condition
Statement[s]
else
Statement[s]
end

1;
2,
2;
3

Here, only the first if block (together with the associated statements) and
the end termination are necessary. The elseif and else blocks are optional.
However, while you may have mutiple elseif blocks, only one else block is
allowed. Also, the conditions are checked in the order they are entered (from
top to bottom), and only those statements associated with the first condition
that is satisfied are executed; MATLAB does not continue checking the
remaining conditions. In MATLAB, any expression that would evaluate to any
value, not just to a Boolean value, can be used as a condition. A zero value
is treated as Boolean "false," and any nonzero value as Boolean "true." Usual
comparison operators <, <=,>, >=, == are all available. Also available are
the logical operators &, |, and ~ for logical "and", "or", and "negation"
operations, respectively. The operator for checking two values for being "not
equal" is ~= in MATLAB. One point to note is that, in MATLAB, these operators
work with general array arguments in the same manner as any arithmetic
operator works. For example:
>> [ 10 5 1 ] > [ 8 5 6 ]
ans =
1
0
0
>> [ 2 0; 50 -3 ] | [ 0 0; 1 10]
ans =
1
0
1
1
>> (1:2:9) <= 5
ans =
1
1
1
0
0
Although this may prove very powerful as a general programming tool, you will
not need to use this feature in this assignment.

Loops: Given the rich set of element-wise operations on arrays, and


operations between arrays, it is not incorrect to say that, in MATLAB, one
would better stay away from running loops of any kind to the extent possible.
This leads to not only simpler coding, but higher computational efficiency as
well. Always remember that MATLAB is an interpreted language. In other words,
the statements in your MATLAB code are read in, processed, and understood one
by one by an interpreter, which subsequently carries out the necessary
computation per each statement. Take as an example the task of computing the
energy of a discrete-time signal x. If you were to do this by using a forloop, then it would take many times longer to get the answer than if you used
the simple sum(x.^2). This is because, when instructed to compute sum(x.^2),
MATLAB essentially executes compiled code after a simple interpretation step,
and the compiled code carries out the costly squaring and addition tasks as
efficiently as they can get. On the other hand, in the case of doing the same
computation using a MATLAB for loop, the cumulative cost of interpretation
becomes far too high as the statements within the loop are interpreted again
and again, and as compiled code is called repeatedly to do a miniscule
computation per call. The trick for good MATLAB programming is, therefore, to
formulate problems in such ways that array or matrix operations can be used
to obtain the solutions. Of course, loops are not always escapable, and they
are okay if the amount of computation per iteration is worth it, or if the
total amount computation is not significant. Take this as a rule of thumb. If
you are turning a long loop in MATLAB to do some miniscule computation per
each iteration step, then the chances are good that there is a better way,
not just in terms of execution speed, but also in terms of code length and
simplicity. All it takes is some forethought to formulate the given problem
right.
This general remark aside, you will want to use loops in this assignment. The
two most common loop constructs in MATLAB are for and while statements, and
their general forms are as given below:
while Condition,
Statement[s];
Some update to affect the Condition in the next round;
end
for var = vector of values for var,
Do something[s] with the variable var;
end
MATLAB's while loop works in the usual way, similarly to a while loop, say,
in C/C++. That is, the Condition is checked at the very beginning, and if it
is not "true," the loop is not entered at all; otherwise, the loop is
entered, and iterations continue until the Condition becomes "false."
MATLAB's for loop, on the other hand, is a little different, as might be seen
by reading the above form as "do something with each value in the vector
supplied." Let us compute the energy of a discrete-time signal x to exemplify
these two types of loops.
energy = 0;
while length(x) > 0,
energy = energy + x(1)^2;
x = x(2:length(x));
end

%
%
%
%
%

initialize
on entry, x has a certain number of elements
add the square of the first sample value
drop the first sample value (done with it)
on exit, x is empty

energy = 0;
for k = 1:length(x),

%
%
%
energy = energy + x(k)^2; %
%
end
%

initialize
for each index value running over the length
of x
add the square of the sample value at the
current index
on exit, x remains the same as on entry

One last note, you could nest loops and/or conditional statements within each
other to implement more complex behavior. You could thus alter the normal
execution of a loop by using conditional continue or break statements within
the loop body. Here, continue causes the remaining statements to be skipped,
and the loop to continue with the next round, and break causes the loop to be
aborted completely. Say, in computing the energy of x, you wish to skip
negative sample values:
energy = 0;
while length(x) > 0,
first = x(1);
x = x(2:length(x));
if first < 0, continue; end
energy = energy + first^2;
end

% update x before possibly skipping over

Say, you wish to compute the energy up to the first negative sample value:
energy = 0;
for k = 1:length(x),
if x(k) < 0, break; end
energy = energy + x(k)^2;
end
Functions: In the previous assignments, you used MATLAB scripts, which ran in
the global scope (workspace). This potentially caused such problems as
conflict among variable names and cluutering of the workspace with temporary
variables, and made you attend to the bookkeeping of variables, their proper
initialization in each script, and cleaning of the temporary ones at the end
of a script. All this trouble could be easily avoided by using functions
instead of scripts as functions run in the local scope. This enables you to
reuse variable names without conflict and freeing you of the need to clear
temporary variables as this happens automatically in a function. In addition
to these advantages, most tasks come naturally with a set of inputs and
outputs, and the most important argument for functions is arguably their
resuability. Imagine modifying a script to play the different musical pieces
of this assignment! The mantra with functions is, no more edit-cut-and-paste,
but write-it-once, run-it-many-times-for-different-inputs. This typically
requires a little bit more effort in the writing phase, but it is worth it.
MATLAB functions are stored in m-files as are MATLAB scripts. However, the
first line (not counting possible leading comment lines) in a function m-file
is a special declaration statement that specifies the inputs and outputs of
your function as well as its name. Although the name of the file need not
match the function name, using the same name for both is common practice, and
it eliminates confusion and possible problems. The following N-input, Moutput function, for example, is meant to be stored in a file named myfunc.m,
which is either in the present working directory or in another directory on
the MATLAB search path.

function [out1,out2, ..., outM ] = myfunc(in1,in2, ..., inN)


% MYFUNC
Short description
%
Long, detailed description
%
...
%
(These leading comment lines are displayed when you call help on
%
this function.)
%
...
Function definition (body):
Statements that work on the inputs variables in1, in2, ..., inN,
and compute values for the output variables out1, out2, ..., outM.
To return the outputs to the calling environment, just assign values
to them.
There is no special command to indicate end of function definition. It
ends and you return to the calling environment when the file ends, or when
another function declaration line is found as in the following (whichever
comes first).
function y = subfunc(x)
You can also have subfunctions available only within the scope of this
file. The input and output variables, x and y, of this subfunction could
have been used in the above function body or in other subfunctions. No
name conflicts would arise.
Now, although the output arguments are returned to the calling environment by
simple assignments to them within the function body, there is a return
command in MATLAB. It causes an immediate return from the function without
execution of the rest of it. This can be useful in conditional termination of
the function's execution, say upon detecting an error. By the way, good
programs test their inputs to make sure that they satisfy any conditions they
are supposed to satisfy. For example, if a particular input argument is to
take non-negative integer values, what will your function do if you pass -3
for this argument? MATLAB's warning and error commands, both of which accept
a message string to be displayed in the command window, are also useful to
communicate such misuse with the caller. (A MATLAB string is a vector of
characters enclosed in single quotes as in 'A string\nAnother one on the next
line'.)
Secondly, how do you make some input arguments optional? The built-in MATLAB
variable nargin is used for this purpose. This variable becomes defined only
within the function body, and it holds the number of input arguments actually
passed by the caller. Checking nargin and seeing that is less than N, the
number of arguments in the declaration line, you can assign default values
for the missing input arguments conditionally. Note though, this works easily
if omissions are from the end of the input argument list. That is, if one
input argument is missing, it is the last one; if two are missing, they are
the last two. So on. Although it is technically possible to come up with more
complex schemes of interpreting different nargin values as meaning different
sets of inputs, take this example along the first, simpler line of thought:
if nargin == 3,
fs = 8192;
elseif nargin ~= 4,
error('myfunc: Wrong number of inputs!');
end

You could use this in your function for Exercise 1 of this assignment to make
the sampling rate an optional input. You could use it in Exercise 2, too,
with a slight modification.
Finally, there is also a nargout variable which similarly holds the actual
number of output arguments queried by the caller. Its usage is similar to
that of nargin. The difference is, omissions of output arguments should
result in the omitted variables' being not assigned values within the
function body. Many of the ADSP toolbox routines as well as many built-in
MATLAB functions employ these techniques.
Miscellaneous: In both exercises of this assignment, the prescribed functions
require generation of a side effect: play out the sampled signal to be
returned. This amounts to nothing other than calling sound before returning
from the functions.
Another MATLAB feature that is useful in this assignment is array
concatenation. Recall the way you enter arrays at the command prompt, e.g., [
1 2 3; 4 5 6 ] for a 2-by-3 matrix. This is nothing but horizontal
concatenation, firstly, of 1-by-1 arrays [1], [2], and [3], secondly, of 1by-1 arrays [4], [5], and [6], resulting in two 1-by-3 arrays, which are
subsequently concatenated vertically. This generalizes to concatenation of
matrices as in the parallel example: [ A1 A2 A3; A4 A5 A6 ]. However, note
that A1, A2 and A3 must have the same number rows so that they can be lined
up side by side horizontally. Likewise for A4, A5 and A6. For the subsequent
concatenation step to work, the sum of the number of columns of A1, A2 and A3
must be equal to that of A4, A5 and A6 as well, so that [ A1 A2 A3 ] and [ A4
A5 A6 ] can be stacked vertically.

ECE381 - SCE/UMKC/WS06

ECE 381: Laboratory 3

Fall 2015

Touch-tone telephone dialing and music synthesis


Part II. Background discussion

MATLAB notes | Background discussion | Assignment

DTMF dial signals: In dual-tone multi-frequency (DTMF) or touch-tone telephone dialing, each keypress is
represented by a dual-frequency signal, which is called a dual-tone simply. The mapping between the keys and the
frequencies are as follows:

To be more precise, one can take the DTMF signal corresponding to a given key k to have the form
x k(t) = cos(2 f L t) + cos(2 f H t), where f L and f H are the low and high frequencies associated with the key k. For
key 6, for example, x 6 (t) = cos(2770t) + cos(21477t). The composite DTMF signal for a sequence of keys, i.e., to a
telephone number, is obtained as the superposition of the individual, truncated and time-shifted dual-tones
corresponding to the numbers. As would be expected from everyday experience with telephones, truncation and time
shifting of individual dual-tones is done in such a way that there is no overlapping of successive dual-tones and there
is a short silence between them. So each dual-tone is heard distinctly.
When it comes to constructing the sampled representation of a composite DTMF signal in the lab, the superposition
task described above reduces to concatenation of sampled representations of individual finite-duration dual-tones. To
represent silence between numbers, one simply inserts an appropriate number of zeros between the sampled dualtones.
Music synthesis: A musical piece is a sequence of notes, which are essentially signals at various frequencies. An
octave covers a range of frequencies from a base pitch f 0 to twice the base pitch, 2f 0 . In the western musical scale,
there are 12 notes per octave, A through G# (or A b ), and they are logarithmically equispaced over the octave. That is,
the frequency of the k-th note in a given octave with the base pitch of f 0 is equal to f k = 2k/12 f 0 , k = 0, 1, 2, ..., 11. This
leads to the following integer encoding of notes within a given octave.
Notes:

A# or
Bb

C #or
Db

D# or
Eb

F#or
Gb

Integer
K:

10

G#
or
Ab
11

The superscripts "#" and "b" are read as sharp and flat, respectively, and each pair of notes with the same integer code
are meant to be at the same frequency. Also observe that the above integer encoding naturally lends itself to
representing sequences of notes covering more than one octave. That is, integers k < 0 and k > 11 indicate,respectively,
notes in a lower and higher octave with respect to the reference octave starting at f 0 . Thus, one can
encode any musical piece as a sequence of integers, and construct a corresponding sampled signal representation,
provided that the reference base pitch f 0 and the duration of each note are all specified. Similarly to the case of the
DTMF dial signals, this entails concatenation of sampled signals corresponding to individual notes.

ECE381 - SCE/UMKC/WS06

As for the general form of the signal for a given note, one can consider a pure tone as the simplest form. That is to
say, for note D, for example, the form is x 5 (t) = cos(2 f 5 t + ). Pure tones, however, will not sound as pleasant as
one would like. To add some color to the sound, consider the improved form x k(t) = (t)cos(2 f kt + ), where (t)
shapes the otherwise flat envelope of the pure tone signal. This helps simulate the attack-sustain-release characteristics
of different instruments, and gives rise to overtones (harmonics) thus enriching the sound. The following figure
exemplifies the envelope forms (t) and simulated notes for woodwind- and string/keyboard-type instruments, where
the duration of the note is normalized to unity.

Can you tell from this figure the longer sustain characterictics of woodwind intruments as opposed to the pronounced
release (decay) characteristics of string or keyboard intruments?
General: Recall, from the previous assignment, that MATLAB's sound function accepts the reconstruction sampling
frequency as an optional second argument. If you do not pass this information to sound explicitly, the default sampling
frequency of 8,192 Hz is assumed. In this experiment, you would do fine with this default value, without risking
aliasing. The highest frequency involved in the DTMF dialing case is 1,477 Hz, which is less than half of 8,192 Hz. In
the case of music synthesis, a base pitch of f 0 = 440 Hz is the standard choice that you might use, and even if you go
as high as three octaves above this value, your highest frequency will be 23 440 = 3,520 Hz, which is still less than
half of 8,192 Hz.
Also recall that sound clips off portions of the input signal exceeding unity in absolute amplitude. Make sure that your
signals are normalized so that all sample values lie in the interval [-1.0,1.0].
School of Computing and Engineering
University of Missouri - Kansas City

Last updated: September,2015

ECE381 - SCE/UMKC/WS06

ECE 381: Laboratory 3

Fall 2015

Touch-tone telephone dialing and music synthesis


Part III. Assignment

MATLAB notes | Background discussion | Assignment

Supplements: getnum.m | woodwind.m | keybrd.m


1. Use MATLAB to solve and plot zero-input responses for various differential equations. Plot x(t) for
D2 y+aDy+9y = 0 for a = 0.1, 1, 3, 6, and 10. First of all, use the MATLAB roots function to solve for the roots
of the differential equation. To make this exercise simpler, assume c=1 whenever a constant is needed and
=0 whenever a phase is needed. Plot these signals using a 5-by-1 subplot arrangement.
For the rest this assignment, you will write two MATLAB functions in which you need to use control structures such
as conditional statements and loops. Consult the MATLAB notes and Experiment 0 if you do not have experience with
these. Also consult the background discussion to learn about the dual-tone multi-frequency (DTMF) dial signals and
music synthesis. The following assignment statements are not complete without some explanations and definitions
made in the background discussion.
2. Write a MATLAB function that constructs and plays the DTMF signal corresponding to a telephone number
composed of digits 0-9, and symbols * and #. The exact specification of your function is as follows:
function dialSig = lastnameLab03Ex1(number,digitDur,silenceDur,fs)
% Usage: dialSig = lastnameLab03Ex1(number,digitDur,silenceDur,fs);
% Inputs: number: Vector of digits to be dialed (i.e., of integers 0,
%
1, ..., 9, 10, and 11, where 10 and 11 represent the
%
symbols * and #, respectively)
%
digitDur: Duration of dual-tone signal per digit in seconds
%
silenceDur: Duration of silence between digits in seconds
%
(must be at least 0.005 seconds)
%
fs: Sampling frequency in Hertz
% Output: dialSig: Sampled dial signal as a column vector
% Side effect: Sampled dial signal is also played out
... Your implementation goes here, after one blank line following the
leading comment lines. ...

In the lab, experiment with different digit and silence durations to make the sound match with your everyday
experience. Your dial signal will be tested by this function:
function y = getnum(x,fs)
%
Y = GETNUM(X,Fs) is the telephone number extracted from the sampled
%
DTMF signal X, where Fs is the frequency in Hertz at which X has been
%
sampled. The default value of 8,192 Hz is assumed if Fs is omitted.

So, as an example, if your function is right, you will see


>> getnum(lastnameLab03Ex1([8 1 6 2 3 5 1 2 3 4],0.3,0.05,8192),8192)
ans =
8162351234

as well as hear the dial signal. If you wish, you can make all but the first input argument to your function
optional.
3. Write a MATLAB function that plays a given sequence of notes, and returns the corresponding sampled music
signal. The exact specification of your function is as follows:
function musicSig =
% Usage: musicSig =
% Inputs: noteSeq:
%
durSeq:
%
%
envType:

lastnameLab03Ex2(noteSeq,durSeq,envType,f0,fs)
lastnameLab03Ex2(noteSeq,durSeq,envType,fs);
Vector of integer-encoded notes to be played
Vector containing the duration (in seconds) of each
note in 'noteSeq'
0 for flat, 1 for woodwind, and 2 for keyboard type

%
envelopes
%
f0: base pitch in Hertz
%
fs: Sampling frequency in Hertz
% Output: musicSig: Sampled music signal as a column vector
% Side effect: Sampled music signal is also played out
... Your implementation goes here, after one blank line following the
leading comment lines. ...

In the lab, play the following four sequences: (All notes, except those with a superscript "+", cover an octave
within a base pitch of your choice. Those superscripted with "+" are meant to be one octave above their nonsuperscripted counterparts.)
1.Raga malkauns(ascending)
Notes:
D
F G
A#+ C + D+
Durations: Equal
3.Big Ben
Notes:
Durations

F#
0.3

D
0.4

4.Pictures at an Exhibition(Mussorgsky)
Notes:
F#
D
Durations
0.3
0.4

2.Raga malkauns(descending)
Notes:
C+
A#+ G
F D
Durations: Equal

E
0.4

A
1

A
0.4

E
0.4

F#
0.3

D
1

E
0.4

A
1

A
0.4

E
0.4

F#
0.3

D
1

If you are into music, feel free to play with anything you like. Try different base pitches and simulated
instruments, and tune the sound to your liking. Also, try different sampling frequencies, and observe the effect.
Submit the two functions you wrote electronically.
School of Computing and Engineering
University of Missouri - Kansas City

Last updated: September, 2015

ECE 381: Laboratory 4


Analog system response using ODE solvers
Part I. Preparatory notes
Matlab offers a rich set of ODE (Ordinary Differential Equation) solvers. You
can enter help funfun at the command prompt to see what is available. These
ODE solvers are indeed quite powerful, and they can be used to solve nonlinear as well as linear ODEs. This assignment is, however, concerned only
with linear, constant-coefficient differential equations (LCCDEs) that
describe linear, time-invariant systems. Here is a brief overview and an
example to help you get going.
First a technical explanation: an ODE the solution of which contains a
rapidly decaying transient term is said to be stiff. Accurate numerical
solution of stiff ODEs requires a very small time step, and hence, it is in
general difficult. However, the rapidity of such decay is relative to the
time interval of interest on which the solution is sought, and it should not
be a cause for concern in this assignment. That is, a non-stiff ODE solver,
e.g., ode23, would be fine for you to work with. Here is the first help
paragraph for this function.
>> help ode23
ODE23 Solve non-stiff differential equations, low order method.
[T,Y] = ODE23(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the
system of differential equations y' = f(t,y) from time T0 to TFINAL with
initial conditions Y0. Function ODEFUN(T,Y) must return a column vector
corresponding to f(t,y). Each row in the solution array Y corresponds to
a time returned in the column vector T. To obtain solutions at specific
times T0,T1,...,TFINAL (all increasing or all decreasing), use
TSPAN = [T0 T1 ... TFINAL].
The second argument TSPAN is understood from this much explanation as the
time interval of interest. You either specify the end points of the interval,
or pass a vector of all time instants at which you wish to obtain the
solution value. The first and the third arguments, ODEFUN and Y0, describe
the equation and the initial conditions, respectively, but they need some
further explanation.
Matlab requires your n-th order differential equation (DE) to be presented as
a system of n first-order DEs. So, a given DE is to be put in this form
first. Take as an example a general second-order LCCDE with a single-term
right-hand side and arbitrary initial conditions:
y''(t) + a1 y'(t) + a2 y(t) = x(t),

where y(0) = y0 and y'(0) = y'0.

By defining z1(t) = y(t) and z2(t) = y'(t), one obtains:


z1'(t) = z2(t) and z2'(t) = x(t) - a1 z2(t) - a2 z1(t),
z2(0) = y'0.

where z1(0) = y0 and

Now, ODEFUN, the first argument to ODE23, is a handler to a Matlab function


that describes such a system of DEs. You need to write this function, and
continuing with the same second-order example, here is what it should look
like:
function dzdt = myfunc(t,z)
dzdt = [ z(2); {rhs}(t) - a1*z(2) - a2*z(1) ];
where {rhs} is a place holder for the forcing function x(t). Note that the
return value dzdt is a column vector containing the derivatives z1'(t) and
z2'(t), and inside the function, you simply express these in terms of z1(t),
z2(t), and x(t). Finally, Y0, the third argument to ODE23, simply contains the
initial conditions for z1(t) and z2(t), in that order.
As for the outputs T and Y from ODE23, you will find the desired solution in
the first column of Y, ready to be plotted against the time vector T:
plot(T,Y(:,1)).
To make this more concrete take the following equation, the solution of which
is sought for 0 t 6.
y''(t) + 5y'(t) + 4y(t) = 6u(t),

where y(0) = 0 and y'(0) = -3.

The function you need to write for this is as follows:


function dzdt = mydiffeq(t,z)
dzdt = [z(2); 6-4*z(1)-5*z(2)];
Now, you are ready to call the ODE solver for the problem:
function runexample(figureNo)
% Just putting everything in a function to avoid cluttering of the work
% and disk spaces.
figure(figureNo); clf;
% Find and plot the total response first.
[t,y] = ode23(@mydiffeq,[0 6],[0 -3]); % note the '@' symbol in front of
% the function name 'mydiffeq'
plot(t,y(:,1),'-');
% solid line for the total response
grid; hold on;
% Find and plot the zero-state and zero-input responses.
[t,y] = ode23(@mydiffeq,[0 6],[0 0]);
plot(t,y(:,1),'--');
% dashed line for the zero-state response
[t,y] = ode23(@mydiffeq0,[0 6],[0 -3]);
plot(t,y(:,1),'-.');
% dot-dashed line for the zero-input response
% Adjust and label the plots.
axis([-.1 6 -.6 1.6]); axesn;
title('DE: y^(^2^)(t)+5y^(^1^)(t)+4y(t)=6u(t), y(0)=0, y^(^1^)(0)=-3');
xlabel('Time, t'); ylabel('Solution, y(t)');
legend('Total response','Zero-state response','Zero-input response',0);
function dzdt = mydiffeq(t,z)

% Local function for finding the zero-state and total responses.


dzdt = [z(2); 6-4*z(1)-5*z(2)];
function dzdt = mydiffeq0(t,z)
% Local function for finding the zero-input response.
dzdt = [z(2); 0-4*z(1)-5*z(2)];
% -- end of runexample.m --------------------------------------------------

In this assignment, you are expected to obtain the solutions numerically as


described above, using ode23.

ECE 381: Laboratory 4

Fall 2015

Analog system response using ODE solvers


Part II. Assignment

Preparatory notes | Assignment

Use Matlab, as explained in the preparatory notes, to numerically evaluate the zero-state, zero-input, and total response
for each of the analog systems described by the following differential equations :
System equation

Excitation

Initial Conditions

Solve for

(a) y''(t) + 5y'(t) + 6y(t) = x(t);

x(t) = 6u(t);

y(0) = 0, y'(0) = 1;

0 t 10.

(b) y''(t) + 5y'(t) + 6y(t) = x(t);

x(t) = 2e -t u(t);

y(0) = 0, y'(0) = 1;

0 t 8.

(c) y''(t) + 4y'(t) + 3y(t) = x(t);

x(t) = 36tu(t);

y(0) = 0, y'(0) = 1;

0 t 2.

(d) y''(t) + 4y'(t) + 4y(t) = x(t);

x(t) = 2e - 2tu(t);

y(0) = 0, y'(0) = 1;

0 t 5.

(e) y''(t) + 4y'(t) + 4y(t) = x(t);

x(t) = 8cos(2t)u(t);

y(0) = 0, y'(0) = 1;

0 t 10.

(f) y'''(t) + 4y''(t) + 5y'(t) + 2y(t) = x(t);

x(t) = e - 2tu(t);

y(0) = 0, y'(0) = 1, y''(0) = 0;

0 t 10.

In each case, obtain the three responses separately for the indicated interval of time, and plot them in one figure, on the
same time axis. Comment on the results. In particular, can you verify the initial conditions from your plots? Do the
zero-state and zero-input responses seem to add up to the total response? Can you identify the transient and steadystate responses in your plots?
Turn in all plots, Matlab scripts and functions. Include your comments and answers to questions.
School of Computing and Engineering
University of Missouri - Kansas City

Last updated: September, 2015

ECE 381: Laboratory 5


Response of a RLC circuit
Assignment

1. Using the MATLAB residue command, determine the inverse Laplace


transform of each of the following functions (C.4.1):

2. Using the feedback system of Fig.4.18d (Page 397) with G(s) = K/(s(s +
8)) and H(s) = 1, determine the transfer function for each of the
following cases:
(a) K = 7
(b) K = 16
(c) K = 80
Hint: Use the MATLAB function tf to determine transfer function.
3.

a. Write down the differential equation for this circuit, in terms


of V0.
b. Find the transfer function of the system.

c. Plot the step response of the system. Is the system under,


critically, or overdamped? What are its poles? Are they real,
imaginary, or complex?
d. Select parameters such that the system is critically damped. Plot
the resulting step response. What are its poles? Are they real,
imaginary, or complex?
e. Select parameters such that the system is overdamped. Plot the
resulting step response. What are its poles? Are they real,
imaginary, or complex?
f. Summarize the relationship between the nature of the poles
(distinct, idential, real, complex?) and the systems behavior.
g. Find the time-domain analytical expression for the step response
of the overdamped circuit. (Use Matlabs help to get the partial
fraction expansion, and then look up Laplace transform pairs.)

ECE 381: Laboratory 6


Filters
Assignment
1. sketch magnitude plots using the abs function .for each part, which
frequencies are strongest? what type of filter would this be called? the transfer
funtions from(4.9-1,page488)-(a),(b),(c).
2. Filter sounds using MATLAB
This exercise uses MATLAB filter design tools to audio.
a. Download filtersound.m, Filter_design.m, and the audio files given in
Blackboard for this lab. Place them in directory on your Q: drive.
b. Start MATLAB and change the path to the path of the files you just
downloaded.
c. Type the command filtersound(trumpet.wav). MATLAB will filter a sound
of a trumpet. It will display the Fourier transform of the trumpet sound
before and after the filtering operation.
d. Play the files trumpet.wav and filt_out.wav to hear the audio before
and after filtering.
e. When the MATLAB function was executed, a plot was displayed of the
Fourier Transform of the trumpet sound. This audio file was created to
play one note, so you can see how harmonics play a role how the audio
sounds. You can also hear the quality of the sound after some of the
harmonics are removed.
- Display the output plot in your report.
- Describe the quality of the output sound after the filter.
3. Use MATLAB tools to design a filter.
a. From the main MATLAB window, choose the Apps tab, then find the Filter
Design & Analysis tool from the drop down menu.
b. Design a high pass filter that will remove the lowest two harmonics from
the trumpet sound.
Choose the following:
- Highpass
- IIR Butterworth
- FS = 44100 (This is the sampling frequency used for CD audio and wav
files).
- Fstop = 1500
- Fpass = 1800
- Astop = 80 dB
- Apass = 1 dB
- The click Design Filter
- Store the file using File/Generate MATLAB Code/Filter Design Function.
Use the filename Filter_design.m and store in the same directory of
other files.
- Then again type the command filtersound(trumpet.wav) from the
MATLAB command line.
-

Display the output plot in your report.


Describe the quality of the output sound after the filter.
What order Butterworth filter was created by the filter design?

4. Use MATLAB tools to design your own filter.


Now use the same tools to create a bandpass filter to pass only the 2nd
and 3rd harmonics from the trumpet sound (those around 1200 and 1800 Hz).
- Describe the design of your filter, including the specifications for
stop and passbands.
- Display the output plot in your report.
- Describe the quality of the output sound after the filter.
- What order Butterworth filter was created by the filter design?
5. Filter your own sounds.
Now obtain your own audio file and filter it using lowpass, highpass, and
bandpass examples. This can be your own mp3 file or you can download
sounds from a site like freesound.org.
For each type of filter (lowpass, highpass, and bandpass), do the
following.
- Describe the design of your filter, including the specifications for
stop and passbands.
- Display the output plot in your report.
- Describe the quality of the output sound after the filter.
- What order Butterworth filter was created by the filter design?
Note that a full audio file will have a wide range of frequencies, not
just the particular harmonics we saw with the trumpet. For the filters,
just pick some range of frequencies to pass or stop.

ECE 381: Laboratory 7


Introduction to Discrete Time Systems
Assignment
1.

Refer to Section M3.1 in the course textbook. Create Figures M3.1


and M3.2. Explain why Figure M3.2 looks as it does.

2.

Use the stem plot in MATLAB to plot the example given in the
course notes where x[n] = u[n] u[n-5]. Also plot x[n-3] and x[-n+2]
over a suitable range of n to show the functions fully.

3.

Use the function in problem 3.M-1 at the end of Chapter 3. Note


that the term downsampling is the same as decimation and upsampling
is the same as interpolation. Plot f[n], f[2n], and f[n/2]. Plot f[n/2]
in two forms fe[n/2] and fi[n/2]. Use linear interpolation. Use a range
on n from -10 to 20. It is recommended that you create a .m file here
instead of trying to use an inline function as the book recommends.
Hint: Use the MATLAB the floor command to round down to the nearest
integer. If a number is an integer multiple of L, then floor(n/L) ==
(n/L) will be true; otherwise it will not be true.

4.

For problem (3), show the difference between the f[t/2] and
fi[n/2]. Use the plot command here instead of the stem command. Use
t = -10:0.01:40 and n=-10:40.

5.

Given is a function x(t) = cos(1000.*pi.*t) which has a frequency


of 500 Hz. Use the following commands plot sampled versions of x(t) for
various sampling rates, fs. Use t=0:0.0001:0.005. Use Nmax = 0.005*(fs)
and n=0:Nmax.
f=inline('cos(1000.*pi*t).*(t>=0)','t');
n = 0:1:0.005*fs; T = 1/fs;
plot(t,f(t),'k',n.*T,f(n.*T),'bo');
stem(n,f(n.*T));
Show the plots and stem plots for sampling frequencies of 250, 500,
1000, 1500, 2000, 3000, 4000, 5000, and 10000 Hz. The sampling rate is
obviously important for providing a sampled DT signal that
appropriately represents the corresponding CT signal. What sampling
rates do you think are needed for this to be true? This is just
supposed to be a guess on your part, but also explain your answer.

ECE 381: Laboratory 8


Discrete-time system response by recursion
Part I. Preparatory notes
Recursion can be used to obtain the response of a discrete-time system
described by a difference equation. The method of recursion is general enough
to deal with nonlinear and/or time-varying systems, and easy enough to
program. However, for linear and time-invariant systems in particular,
Matlab's filter function does most of the job for you. Even more useful is
dtsim, which hides certain technicalities of the filter function from the
user. Besides, it returns the total, zero-state, and zero-input responses
separately in one call. Check out the help on this function. There are
different ways for using this function as explained below.
Consider a discrete-time system described by a general, N-th order, linear
constant-coefficient difference equation
A0 y[n] + A1 y[n-1] + + AN y[n-N] = B0 x[n] + B1 x[n-1] + + BM x[n-M]
and initial state y[-1], y[-2], ..., y[-N]. Let A and B be Matlab vectors
storing the coefficients of the output and input terms in the difference
equation, respectively. Also let IC be the vector of initial conditions. Now,
if XN stores the input signal x[n] over an index range, say, 0 n < K, then
the total system response y[n] over the same index range is obtained by
YN = dtsim(B,A,XN,IC);
By calling dtsim with three output arguments, you can get the zero-state and
zero-input responses, YZS and YZI, in addition to the total response YN, all
computed over the same index range as the input XN. If you omit the input
argument IC, the system is assumed to be in relaxed state initially. The
following commented examples illustrate such different uses of dtsim:
YZS = dtsim(B,A,XN,zeros(1,N));
YZS = dtsim(B,A,XN);
YZI = dtsim(B,A,zeros(1,K),IC);
YN = YZS + YZI;
[YN,YZS,YZI] = dtsim(B,A,XN,IC);

%
%
%
%
%
%
HN = dtsim(B,A,[1 zeros(1,K-1)]); %

zero-state response
zero-state response
zero-input response for 0 n < K
total response
most general call (all three responses
in one shot)
impulse response to K terms

An alternative way for obtaining the impulse response h[n] of the system to K
terms, i.e., over the index range 0 n < K is as follows:
HN = dtsim(B,A,K);
Before doing an example, there is one quirk of dtsim that needs to be noted:
it requires the coefficient vectors A and B to be of the same length. The
general form of the diffence equation given above assumes that the leading
output and input terms are y[n] and x[n], respectively. Consequently, the
corresponding coefficient vectors are understood to start as A = [ A0 A1 A2 ...

] and B = [ B0 B1 B2 ... ]. Any deviation from this general form would have to
be reflected by including leading zero coefficients in A or B as needed.
However, dtsim requires inclusion of trailing zeros as well so that both A
and B have the same number of elements. Take the following examples
illustrating this point (correct coefficient vectors are indicated by bold
typeface):
y[n] = x[n-2]
>
A = 1;
B = [0 0 1];
A = [1 0 0];
B = [0 0 1];
y[n] = x[n+1]
>
A = [0 1];
B = 1;
A = [0 1];
B = [1 0];
y[n] - 2y[n-1] = x[n+1] + 2x[n] x[n-2]

>

A = [0 1 -2];
B = [1 2 0 -1];
A = [0 1 -2 0]; B = [1 2 0 -1];

Now, take the following example:


y[n] + 0.7y[n-1] + 0.1y[n-2] = x[n];
2] = 3.
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>

x[n] = (0.5)n u[n];

n = 0:10; x = 0.5 .^ n;
[yt,yzs,yzi] = dtsim([1 0 0],[1 .7 .1],x,[0 3]);
figure(1); clf;
subplot(3,1,1);
dtplot(n,yt,'o'); ylabel('Total');
axis([-.5 10.5 -.1 .9]); axesn;
title('Problem 5.9.c');
subplot(3,1,2);
dtplot(n,yzs,'o'); ylabel('Zero-state');
axis([-.5 10.5 -.5 1.2]); axesn;
subplot(3,1,3);
dtplot(n,yzi,'o'); ylabel('Zero-input');
axis([-.5 10.5 -.4 .41]); axesn;
xlabel('Index n');

y[-1] = 0, y[-

Also see the example below. Its about smoothing effects of a moving average
filter. Exercise 4 in this assignment is about minimizing such undesired
variations superimposed on a signal due to random noise. Filtering in general
is a commonly used technique to minimize noise effects, and a moving average
filter is probably the simplest form of filtering that could be used for this
purpose. In Exercise 4, you will try out different forms of filtering for
noise suppression.
Consider a 20 point moving average FIR filter y[n]=1/20{x[n]+x[n1]+.....+x[n-19]}. It is also called a smoothing filter because it tends to
smooth out the rapid variations in a signal. To confirm its smoothing
property, try the following:
1.
2.
3.
4.

Generate 200 samples of a 1-Hz sine wave sampled at 40Hz.


Add some noise to generate a noisy signal.
Filter the noisy signal through the 20 point filter.
Plot each signal to display the effects of noise and smoothing.

n=0:199;
x=sin(2*pi*n*0.025); x=x(:);
xn=x+0.5*randist(x,'uni');
a=[1 zeros(1,19)];
b=0.05*ones(1,20);
y=filter(b,a,xn);
plot(n,x);
plot(n,xn,n,y

ECE 381: Laboratory 8

Fall 2015

Discrete-time system response by recursion


Part II. Assignment

Preparatory notes | Assignment

Download the following files to the local directory - dtsim, dtplot, sysresp1, axesn, randist
1. A relaxed discrete-time system is described by the following difference equation:
y[n] - 0.64y[n-2] = 2x[n] + x[n-1].
Obtain the impulse response h1 [n] of this system for 0 n 20. Use the function dtsim as
explained in the preparatory notes. Make a stem plot of h1 [n] versus n. (You can use stem
or dtplot for that.)
2. Another relaxed discrete-time system is described by the following
difference equation:
2y[n] - 1.28y[n-2] = x[n].
Obtain the impulse response h2 [n] of this system for 0 n 20 using dtsim as in Exercise
1, and similarly, make a stem plot of h2 [n] versus n.
3. Explain the relationship between h1 [n] and h2 [n] obtained in Exercises 1 and 2,
respectively. In particular, can you express h1 [n] in terms of h2 [n]? Verify your answer
numerically.
4. This exercise is about filtering out the noise from a discrete-time signal corrupted
by a zero-mean white noise process.
a. First, construct a MATLAB vector for the noise-free signal s[n] = 0.1n +
sin(0.1n), 0 n 60:
b.

n = 0:60; sn = 0.1*n + sin(0.1*n*pi);

Next, construct a vector, the same size as for s[n], of zero-mean uniformlydistributed noise samples. Call this noise signal w[n]. Add w[n] to s[n] to obtain the
noisy signal. Call the noisy signal x[n]:
wn = rand(size(sn)); %
%
%
wn = wn - 0.5;
%
wn = a*wn;
%
%
xn = sn + wn;

rand(M,N) returns an M-by-N matrix of pseudorandom numbers uniformly distributed over the
interval [0,1)
subtract 0.5 to make zero-mean noise
multiply by a to make noise stronger (a > 1)
or weaker (0 < a < 1)

Now, plot the original noise-free signal and its noisy version in one figure on the
same axis. Do not use stem
plots, but instead, use the regular plot function. Also compute the SNR (signalto-noise ratio) and write it in the figure title:
plot(n,sn,'- .',n,xn,'-');
snr = sum((sn-0.1*n).^2);
% pure
sinusoidal power in the signal snr =

10*log10(snr/sum((xn-sn).^2)); % divide by noise


power title(['Lab06Ex4a: Original noisy signal
(SNR = ' ...
num2str(snr) ' dB)']);

c. Now consider the 4-point moving average filter


y[n] = 0.25x[n] + 0.25x[n-1]
+ 0.25x[n-2] + 0.25x[n-3].
Filter the noisy signal x[n] of part a using this filter. That is, obtain the system
response using dtsim . Assume zero initial state. Plot the filtered signal y[n] on the
same axis with the original signal s[n], as done in part a, with the SNR written in
the figure title.
d. Repeat part b using the 4-point weighted moving average filter

y[n] = 0.4x[n] + 0.3x[n-1] + 0.2x[n-2] + 0.1x[n-3].

e. Repeat part b using the recursive exponential averaging filter


y[n] - 0.6y[n-1] = 0.4x[n].
Comment on the results. In particular:
i. Based on the results obtained, evaluate the above filters in terms of their
noise suppression capabilities. ii. Suggest an extended experiment to test (prove
or disprove) your conclusions in i.
iii. Can you identify other measures of performance for these noise suppression
filters? (Trying small values for parameter a would be helpful.)
Turn in all plots, MATLAB scripts and/or functions. Include your comments and answers
to questions.

ECE 381: Laboratory 9


Discrete Time difference equation and convolution

I.

FALL 2015

Numerical solutions of Discrete-time Difference Equations using


MATLAB

1. Solve the following difference equation numerically using MATLAB.


Show the stem plot for the result for n=-5:1:10
y[n] -1.1y[n-1] +0.3y[n-2]=0;

y[-1]=9, y[-2]=49/3

Refer to Computer Example C3.3 on page 274 of the course


textbook for help.
2. Because the difference equation in (1) has no input, the output y[n]
is also the zero-input response.
The zero-input response to this equation was derived in class
as
y[n]=(2.*(.5).^n+3.*(0.6).^n).*u[n]
Show this result on a stem plot also to show that this
equation matches the result found for part (1). Note,
however, that the closed form expression of y[n] that is
given here only applies for n>=0, so you must append values to
y to also account for values of n in -5<=n<=-1.
II. The MATLAB filter function
3. MATLAB includes a "filter" function that allows one to
provide the a and b coefficients from a difference equation
and produce the filtered output of x[n] that results from
using that transfer function. Recall that the a coefficients
would come from Q(E) in
4.
Q(E)y[n]=P(E)x[n] and b's from P(E).
The form of filter is "h = filter(b,a,x(n))" where b and a
are vectors of coefficients b = [b0 b1 b2 ...] and a = [1
a1 a2 ...]. Use "help filter" in MATLAB if more information
is needed.
Show the output of the MATLAB filter function for the
following difference equation.
y[n] - 0.6y[n-1] -0.16y[n-2] = 5x[n]
x = inline('n==0') which means x is the DT impulse function
5. Using the approach you used in problem (1), show the output
of the difference equation in problem (3) and show
that the results are the same.
III. Convolution using MATLAB

6. Refer to Computer Example C3.7 in the course textbook in page 299.


This describes the DT convolution function that is available in
MATLAB. Show a stem plot for the convolution of the following two
signals. Make sure to appropriately label the time axis n.
x[n] = (0.8).^n.*(u[n] - u[n-20])
h[n] = u[n-3]-u[n-20]
7. Refer to the lecture notes for Section 3.8 where a convolution example
very similar to this was given. There the answer was -5.*((0.8).^(n-2)1).*u[n-3]. Plot that result for 0<=n<=40 and compare it to the plot for
problem (5). Explain where and why the plots are similar and where and why
the plots are different.
IV. Using MATLAB to Find the Zero-state Response
8. Now as a final exercise we wish to use MATLAB to find the zero-state
response of a system. This involves (1) finding the impulse response, and (2)
finding yzs[n] as the convolution of h[n] and x[n]. Find and show the stem
plot for zero-state response of the following difference equation.
y[n] - 5y[n-1] +6y[n-2] = x[n-1] + 5x[n-2]
x[n] = (3.*n+5).*(n>=0)
(a)
(b)

Show the stem plot for the impulse response.


Show the stem plot for the zero-state response yzs[n] =
x[n] * h[n]

9.Confirm your results in (8)using Z-transforms.

ECE 381: Laboratory 10


Fourier Series and Fourier transform

FALL 2015

1. Plot the Fourier series for the following signal studied in class.

ao = 1, an = 0, bn=-2/ n
Plot for 1, 2, 10 and 100 harmonics.
Note: First harmonic is fundamental at fo.
2. Plot the Fourier series for example 6.4 (page 607) in the text for 1, 2, 10, 50 and
harmonics.
3. Compare the results in (1) and (2). Which ones uses relatively fewer harmonics to get to a
close approximation to the original? Why do you think that is true? Which of the signals would
you say has a larger bandwidth?
4. The Fourier transform of the unit pulse is the sinc function.
Consider the x (t) as given below.

a. plot the x(t) for = 1.5, = 2.


b. Plot the sinc functions for the given values of = 1.5, = 2.
Shown below is the program for = 1.
Use M7.1 (Page 754). What happens when you change the width of the Signal?

ECE 381:Laboratory 11

FALL 2015

Sampling, DFT and FFT

1. Sampling. Using subplots, on the top show three cycles of a 1 Hz cosine. On the
bottom, show a sampled version of that signal on a stem plot as follows. You will
end up with three figures.
a. Sampled below the Nyquist rate.
b. Sampled at the Nyquist rate.
c. Sampled above the Nyquist rate.
Hint: Use Ts as the appropriate sampling interval to match the sampling rates above.
The sampled equation would be of the form cos(2.*pi.*n.*Ts).
2. Create a vector n=0:N0-1 where N0 = 64. Plot a stem plot of the Discrete Fourier
Transform of x= cos(2*pi*n/16) using the MATLAB fft (Fast Fourier Transform) command.
Also plot for N0=128, and N0=256.
a. What happens when you change the number of samples?
b. Show that these plots exhibit the symmetry of the DFT.

3. Given is the following MATLAB code for preparing a DFT of a cosine. For each plot,
use a stem plot with r on the x-axis.
fL=5.5;
fs=8*fL;
Ts=1/fs;
f0=0.5;
%
T0=1/f0;
%
N0=round(T0/Ts); %
n=0:N0-1;
r=n.*f0;
%

% Frequency of sinusoid
% Sampling frequency
% Sampling interval
Frequency resolution of the DFT
Duration of the sampling window
Number of samples
Frequency for each DFT point

x=cos(2*pi.*fL*(n.*Ts)); % Signal
a. Plot the fft of this sinusoid.
b. Plot the fft when you change the frequency resolution to 1.0 Hz.
c. Plot the fft when you change the frequency to 5.4 Hz with the resolution at 0.5
Hz.
d. Compare the plots for (a), (b), and (c). How are they different and why?
e. Describe how you would change the parameters in (b) and (c) to look like (a)
(with different values from (a)) and show the result.
4. Use the signal in (3a) and implement zero padding. Show the stem plot of the FFT
when using padding to make the vector x longer by: 2 times, 4 times, and 10 times.
Each time the vector r should be adjusted for the new number of samples. The peaks in
(3a) should be at the some location in these plots. For the case of 10 times, also
zoom around the first peak to show more detail.
5. The Fast Fourier Transform is a version of the DFT which implements faster
calculations when N0 is a power of 2. Determine how much speed improvement is
created.

a.Create a signal like x in part (3) with a vector n of 1024 values. Run the fft
of this signal 20 times and record the time elapsed. This can be accomplished by
running the MATLAB tic command before the loop and toc command after the loop.
b.Do the same as (a) above but with a vector with 1023 values.
c.What is the difference in the amount of time for the calculations.

Você também pode gostar