Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 1 SP19

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

1 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Digital Signal Processing

Lab-1 Manual

Introduction to Discrete Time Signal


Processing on MATLAB
2 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Introduction to Discrete Time Signal


Processing on MATLAB

Objective
This introductory lab allows students to understand the basic concept of the discrete-time
signals and their representation on MATLAB. Furthermore, it demonstrates some basic
MATLAB codes in order to achieve hands-on it.

Pre-Lab Work
MATLAB is a high-level programming language that has been used extensively to
solve complex engineering problems. The language itself bears some similarities with
ANSIC and FORTRAN.
MATLAB works with three types of windows on your computer screen. These
are the ‘Command window’, the Figure window and the Editor window. The Figure
window only pops up whenever you plot something. The Editor window is used for
writing and editing MATLAB programs (called M-files) and can be invoked in
Windows from the pull-down menu after selecting File |New| M-file. In UNIX, the
Editor window pops up when you type in the command window: edit filename
(‘filename’ is the name of the file you want to create).
The ‘ Command window’ is the main window in which you communicate with
the MATLAB interpreter. The MATLAB interpreter displays a command >>
indicating that i t is ready to accept commands from you.
• View the MATLAB introduction by typing
>> intro
at the MATLAB prompt. This short introduction will demonstrate some basic
MATLAB commands.
• Explore MATLAB’s help capability by trying the following:
>> help
>> help plot
>> help ops
>> help arith
• Type ‘demo’ and explore some of the demos of MATLAB commands.
3 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

• You can use the ‘command’ window as a calculator, or you can use it to
call other MATLAB programs (M-files).

Say you want to evaluate the expression a3 + √bd-4c, where a=1.2, b=2.3, c=4.5 and
d=4. Then in the ‘command’ window, type:
>> a = 1.2;
>> b=2.3;
>> c=4.5;
>> d=4;
>> a^3+sqrt (b*d)-4*c
ans=
-13.2388
Note the semicolon after each variable assignment. If you omit the semicolon, then
MATLAB echoes back on the screen the variable value.

1. Special characters and functions


Some common special characters used in MATLAB are given below:

Symbol Meaning
Pi π (3.14...)
Sqrt indicates square root e.g., sqrt(4)=2
ˆ indicates power(e.g., 3ˆ2=9)
Abs Absolute value | .| e.g., abs(-3)=3
NaN Not-a-number, obtained when comparing mathematically undefined op-
ererations, such as 0/0
Inf Represents +∞
; Indicates the end of a row in a matrix. It is also used to suppress
printing on the screen (echo off )
% Denotes a comment. Anything to the right of % is ignored by the
MATLAB interpreter and is considered as comments
’ Denotes transpose of a vector or matrix. It’s also used to define strings,
e.g.,str1=’DSP’;
4 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

2. Handling Complex Numbers in MATLAB


MATLAB also supports complex numbers. The imaginary part of the signal can be
represented with the symbol i or j , assuming that you did not use these symbols
anywhere in your program (that is very important!). Try the following:
>> z=3 + 4i % note that you do not need the ‘*’ after 4
>> conj (z) % computes the conjugate of Signal z
>> angle (z) % computes the phase of Signal z
>> real (z) % computes the real part of Signal z
>> imag (z) % computes the imaginary part of z
>> abs (z) % computes the magnitude of Signal z
You can also define the imaginary number with any other variables you like. Try the
following:
>> img = sqrt (-1)
>> z = 3+4*img
>> exp(pi*img)

3. Handling Arrays/Vectors in MATLAB


3.1. Arithmetic Operations
There are four different arithmetic operators:
+ addition
− subtraction
* multiplication
/ division (for matrices it also means inversion)
There are also three other operators that operate on an element by element basis:
.* multiplication of two vectors, element by element
./ division of two vectors, element-wise
.^ raise all the elements of a vector to a power.
Suppose that we have the vectors x = [x1, x2 , ..., xn ] and y = [y1 , y2 , ..., yn ]. Then

x. ∗ y = [x1 y1 , x2 y2 , ..., xn yn ]
5 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

x./y = [x1/ y1 , x2/ y2 , ..., xn/ yn ]

x.ˆp = [xp , xp , ..., xp ]


1 2 n

The arithmetic operators + and — can be used to add or subtract matrices, scalars or
vectors. By vectors we mean one-dimensional arrays and by matrices we mean multi-
dimensional arrays. This terminology of vectors and matrices comes from Linear
Algebra.
Example:
>> X=[1,3,4]
>> Y=[4,5,6]
>> X+Y

ans = 5 8 10
To compute the dot product of two vectors, you can use the multiplication operator *. For
the above example, it is:
>> X*Y’
ans= 43
Note the single quote after Y. The single quote denotes the transpose of the matrix or a
vector.
To compute an element by element multiplication of two vectors (or two arrays) you
can use the .* operator:
>> X .* Y

ans = 4 15 24
That is, X.*Y means [1×4, 3×5, 4×6] = [4 15 24]. The ‘.*’ operator is used very
often (and is highly recommended) because it is executed much faster compared to
the code that uses for loops.

3.2. Array Indexing


In MATLAB, all arrays (vectors) are indexed starting with 1, i.e., y(1) is the first
element of the array y.
Note that the arrays are indexed using parenthesis (.) and not square brackets [.] as
in C/C++. To create an array having as elements the integers -5 through 5, just
enter:
>> x= [-5,-4,-3,-2,-1,0,1,2,3,4,5]
6 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Alternatively, you can use the : notation,


>> x = -5:5
The : notation above creates a vector starting from 1 to 6, in steps of 1. We can
visualize the array ‘x’ and its indexes by the following table:

array ‘x’ -5 -4 -3 -2 -1 0 1 2 3 4 5

indexes of ‘x’ 1 2 3 4 5 6 7 8 9 10 11

If you want to create a vector from 1 to 6 in steps of say 2, then type:


>> x = 1:2:6
ans= 3 5
Try the following code:
>> jj= 2 : 4 : 17
>> jj=20 : -2 : 0
>> ii=2 : (1/10) : 4
Extracting or inserting numbers in a vector can be done very easily. To concatenate
an array, you can use the [ ] operator, as shown in the example below:
>> x=[1:3, 4, 6, 100:110]
To access a subset of the array, try the following:
>> x(3:7)
>> length(x) % gives the size of the array or vector
>> x(2:2:length(x)

3.3. Allocating memory


You can allocate memory for one-dimensional arrays (vectors) using the zeros
command. The following command allocates memory for a 100-dimensional array:
>> Y=zeros (100,1);
>> Y (30)

ans = 0
Similarly, you can allocate memory for two-dimensional arrays (matrices). The
command
7 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

>> Y=zeros (4,5)


defines a 4 by 5 matrix. Similar to the zeros command, you can use the command
ones to define a vector containing all ones,
>> Y=ones (1,5)

ans= 1 1 1 1 1
Note: Memory allocation is needed when in your code you have to refer to some
variable which has not been created yet. If in such cases you proceed with referring
the variable without first allocating memory for it the MATLAB will generate an
error saying ‘unknown variable’. So the commands zeros, ones and randn may be
used to allocate this space.

4. Conditional Statements and Loops


MATLAB has the following flow control constructs:

 if statements
 switch statements
 for loops
 while loops
 break statement
The if, for, switch and while statements need to terminate with an end statement.

Examples:
IF:

x=-3;

if x>0

str = ‘positive’;

elseif x<0

str = ‘negative’;

elseif x = = 0

str = ‘zero’;

else

str = ‘ Not a real number’;

end

a. What is the value of ’str’ after execution of the above code?


8 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

WHILE:
x=-10;
while
x<0
x=x+1;
end
b. What is the value of x after execution of the above loop?
FOR loop:
X=0;
for i = 1:10
X=X+1;
end
The above code computes the sum of all numbers from 1 to 10.
BREAK:
The break statement lets you exit early from a for or a while loop:
x = -10;
while x < 0
x = x + 2;
if x = = -2
break;
end
MATLAB supports the following relational and logical operators:

Conditional and Logical Operator

Meaning Symbol

Less than equal <=

Less than <

Greater than equal >=


9 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Greater than >

Equal ==

Not equal ˜=

AND &

OR |

NOT ˜

Write a code that print your name five times using FOR loop and WHILE loop.

5. Plotting:
You can plot arrays using MATLAB’s function plot. The function plot (.) is
used to generate line plots. The function stem(.) is used to generate “picket-fence”
type of plots. Example:
>> x=1:20;
>> plot(x) %see Figure 1
20

18

16

14

12

10

0
0 2 4 6 8 10 12 14 16 18 20

Figure 1: Plot obtained using the plot command.


>> stem(x) % see Figure 2

20

18

16

14

12

10

0
0 2 4 6 8 10 12 14 16 18 20

Figure 2: Plot obtained using the stem function.


10 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Example of a plot generated using the plot command is shown in Figure 1, and
example of a plot generated using the stem function is shown in Figure 2. More
generally, plot(X,Y) plots vector Y versus vector X. Various line types, plot
symbols and colors may be obtained.
using plot(X,Y,S) where S is a character string indicating the color of the line,
and the type of line (e.g., dashed, solid, dotted, etc.). Examples for the string S
include:

r Red + plus −− dashed


g green * star
b blue s square

You can insert x-labels, y-labels and title to the plots, using the functions
xlabel(.), ylabel (.) and title (.) respectively. To plot two or more graphs on the
same figure, use the command subplot.
The subplot (m, n, p) argument in the subplot command indicates that the figure
will be split in ‘m’ rows and ‘ n’ columns. The ‘p’ argument takes the values 1, 2,
. . . , m × n. In the example above, m = 2, n = 1,and, p = 1 for the top figure and
p = 2 for the bottom figure. For instance, to show the above two plots in the same
figure, type:
>> subplot(2,1,1), plot(x)
>> subplot(2,1,2), stem(x)

20

15

10

0
0 2 4 6 8 10 12 14 16 18 20

20

15

10

0
0 2 4 6 8 10 12 14 16 18 20

Figure 3: Output of the subplot(2,1,p) command.


To get more help on plotting, type: ‘help plot’ or ‘ help subplot’.
11 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

6. Programming in MATLAB (M-File):


MATLAB programming is done using M-files, i.e., files that have the extension .m.
These files are created using a text editor. To open the text editor, go to the File
pull-down menu, choose ‘New’, then ’M-file’. After you type in the program, save
it, and then call it from the command window to execute it. Say for instance that
you want to write a program to compute the average (mean) of a vector x. The
program should take as input the vector x and return the average of the vector.
You need to create a new file, called “average.m”. If you are in Windows, open
the text editor by going to the File pull-down menu, choose New, then M-file. If
you are in UNIX, then type in the command window: edit average.m. Type the
following in the empty file:
function y = average (x)
L=length(x);
sum = 0;
for i = 1:L
sum = sum + x(i);

end

y = sum /L; % the average of x


Remarks:
y — is the output of the function “average”
x — is the input array to the function “average”
average — is the name of the function. It’s best if it has the same
name as the filename. MATLAB files always need to have the
extension .m
1. From the Editor pull-down menu, go to File|Save, and enter: average.m for
the filename.
2. Go to the Command window to execute the program by typing:
>> x=1:100;
>> y=average(x)
ans =
50.500
Note that the function average takes as input the array x and returns one number, the
12 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

average of the array. In general, you can pass more than one input argument and
can have the function return multiple values. You can declare the function average,
for instance, to return 3 variables while taking 4 variables as input with the
following statement:
function [y1, y2, y3] = average(x1,x2,x3,x4)
In the command window it has to be invoked as:
>> [y1, y2, y3] = average(x1,x2,x3,x4)

7. Loading and saving data:


You can load or save data using the commands load and save. To save the variable
x of the above code in the file data.mat, type:
>> save data.mat x
Note that MATLAB’s data files have the extension .mat. To retrieve the data that was
saved in the vector x, type:
>> load data.mat
The vector x is loaded in memory. To see the contents of memory use the command
whos:
>> whos
Name Size Bytes Class
X 1x8193 65544 double array
array
Grand total is 8193 elements using 65544 bytes
The command whos gives a list of all the variables currently in memory, along with
their dimension. In our case, x contained 8193 samples.
To clear up memory after loading a file, you may type clear all when done.That is
very important, because if you do not clear all the variables in memory, you may run
into problems with other programs that you will write that use the same variables.

In-Lab Work:
A signal is a function that conveys some useful information about the behavior or
attributes of some phenomenon. Signals are mathematically represented as a function of
one or more independent variables i.e. y =ƒ( .., ) where .., are the
independent variables that could be time or space and ‘y’ is the independent variable that
in this case represent the signal values. In this lab, we will mostly be dealing with signals
which are the function of time only and in case of discrete signals, we will replace time
with the variable ‘n’ which will only take discrete values.
13 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

1. Signals in MATLAB
Signals are divided into two major types.

1.1. Analog Signals


If either of the independent (Time) or dependent (Signal values) variables are continuous,
the signal is termed as analog. In this lab, we will mostly be dealing with discrete time
signals.

MATLAB representation
Output:
In MATLAB, signals are represented by using two
variables i.e. y=sin (t) where variable‘t’ represents the
time axis and ‘y’ represents the signal values.
>> t=0:0.01:7;
>> y=sin(t);
>> plot(y)

1.2. Digital signals


If both independent (Time) or dependent (Signal
values) variables are discrete, the signal is termed as Output:
digital. Digital signals uses discrete or discontinuous
values to represent information.

MATLAB representation:
>> n=0:7;
>> y=sin(n);
>> stem(n,y)

2. Some fundamentals sequences


2.1. Impulse Sequence
How to generate an impulse sequence δ [n- n0] for a finite length [-10 to 9], where ‘n’
represents the discrete-time axis and ‘n0’ is the delay.
Initialize a vector ‘n’ containing value from -10 to 9.
Initialize an input array ‘x’ containing all zeros of length ‘n’.
Find the index when ‘n’ is equal to the 0, and save its value into a variable ‘i’.
If ‘n0’ is less than 0
14 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

 Replace ‘0’ by ‘1’ in an array ‘x’ at an index ‘i + n0’.


Else- If ‘n0’ is greater than 0

 Replace ‘0’ by ‘1’ in an array ‘x’ at an index ‘i + n0’.


Else

 Insert ‘1’ in an array ‘x’ at an index ‘i ‘

 Plot the array ‘x’ w.r.t ‘n’ and label its axis.

2.2. Step Sequence


How to generate a step sequence u [n- n0] for a finite length [-10 to 9], where ‘n’ is a
discrete-time axis and ‘n0’ is the delay.
Initialize a vector ‘n’ containing value from -10 to 9.
Initialize an input array ‘x’ containing all zeros of length ‘n.’
Find the index when ‘n’ is equal to the 0, and save its value into a variable ‘i’.
If ‘n0’ is less than 0

 Replace ‘0’s by ‘1’s in an array ‘x’ starting from the index ‘i + n0’ upto
the last index of the array.
Else- If ‘n0’ is greater than 0

 Replace ‘0’s by ‘1’s in an array ‘x’ starting from the index ‘i - n0’ upto the
last index of the array.
Else

 Replace ‘0’s by ‘1’s in an array ‘x’ starting from the index ‘i’ upto the last
index of the array.
Plot the array ‘x’ w.r.t ‘n’ and label its axis.
Note: The value of the delay ‘n0’ must not exceed the maximum or minimum value
of the vector ‘n’ i.e from above mentioned cases ‘n0’ should lie exceed 9 or 10
(ignoring the negative sign of the negative values).
15 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Lab Tasks
In-Lab Task-1: Generate a Continuous time cosine signal and plot it.

In-Lab Task-2: Generate a Discrete time exponential signal and plot it.

In-Lab Task-3: Write a MATLAB program for the ‘running average’, a running
total is a sequence of partial sum of a given sequence/signal. For example, the running
totals of the signal {a, b, c, …}are a, a+b, a+b+c, ... Use that program to find the
running total of the discrete time signal of length N=100. Write your program
so that it is
flexible. That is, you should be able to invoke your program from the command
window as follows:
16 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

>> y=running_averagel(x)
where x is the input signal, and y is the running total of that signal.

Post-Lab Task-1: Write a program to compute the variance and mean of a


signal x. The variance σ is defined to be:

where ‘ m ’ is the mean value of the signal x. For signal x, use all the integers from
1 to 1000.
17 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Post-Lab Task-2: Can you explain what the following


program does: L = length(x);
for i = 1: L
if x (i) < 0
x (i) = -1;
end
end

Post-Lab Task-3: Generate a step sequence u [n] as described in In-Lab section, use it
to generate an impulse as δ [n] = u[n] – u[n-1].
18 DSP Lab Manuals 2016, Electrical Engineering Department, COMSATS Institute of IT, Islamabad

Post-Lab Task-4: Generate an impulse sequence δ [n] as described in In-Lab


generate a step sequence
section, use it to

You might also like