0% found this document useful (0 votes)
267 views

DSP Lab 1 - 03

This document is an introduction to discrete time signal processing using MATLAB. It provides an overview of MATLAB basics like data types, arithmetic operations, arrays, conditional statements and loops. It also describes key MATLAB functions for signals like zeros, ones and randn for memory allocation and complex number handling functions like conj, angle, real, imag and abs. The objective is for students to understand basic discrete time signals and their representation in MATLAB through hands-on practice.

Uploaded by

Abdul Basit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
267 views

DSP Lab 1 - 03

This document is an introduction to discrete time signal processing using MATLAB. It provides an overview of MATLAB basics like data types, arithmetic operations, arrays, conditional statements and loops. It also describes key MATLAB functions for signals like zeros, ones and randn for memory allocation and complex number handling functions like conj, angle, real, imag and abs. The objective is for students to understand basic discrete time signals and their representation in MATLAB through hands-on practice.

Uploaded by

Abdul Basit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

EEE324 Digital Signal Processing

Lab # 01: Introduction to Discrete Time Signal


Processing on MATLAB

Name Abdul basit

Registration Number FA18-BEE-002

Class BEE-6A

Instructor’s Name Ma’am Nida Zamir

Lab Assessment
Post Lab Total
Pre-Lab In-Lab Data
Data Analysis Writing Style
Presentation

Details of Group Members


Abdul Basit FA18-BEE-002

Hareem Safdar FA18-BEE-048

COMSATS Institute of Information Technology 1


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Lab # 01 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
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 pulldown
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 it 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

COMSATS Institute of Information Technology 2


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

• Type ‘demo’ and explore some of the demos of MATLAB commands.

Page

• 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:

Symbo Meaning
l
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 o )
% 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,

COMSATS Institute of Information Technology 3


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

e.g.,str1=’DSP’;

2. Handling Complex Numbers in MATLAB

MATLAB also supports complex numbers. The imaginary part of the signal can be
represented with the alphabet j assuming. Try commands given in following:

>> z=3 + 4i % note that you do not need the ‘*’ after 4 Page

>> 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

COMSATS Institute of Information Technology 4


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

./ division of two vectors, element-wise

.^ raise all the elements of a vector to a power.

Suppose that we have the vectors x = [x 1, x2, ..., xn] and y = [y1, y2, ..., yn]. Then x. y =

[x1y1, x2y2, ..., xnyn]

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-

COMSATS Institute of Information Technology 5


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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]

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

COMSATS Institute of Information Technology 6


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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

>> x = 1:2:6 ans= 3

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

>> 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

COMSATS Institute of Information Technology 7


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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 = ‘negstive’;
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?

WHILE:

x=-10; while

x<0 x=x+1;

end

b. What is the value of x after execution of the above loop?

COMSATS Institute of Information Technology 8


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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 >=

Greater than >

Equal ==

Not equal ˜=

AND &

OR |

NOT ˜

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

5. Plotting:

COMSATS Institute of Information Technology 9


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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

Figure 2: Plot obtained using the stem function.

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 −− dashe


d
g gree * star
n
b blue s squar
e

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.
COMSATS Institute of Information Technology 10
Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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)

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

To get more help on plotting, type: ‘help plot’ or ‘help subplot’.

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 pulldown 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

COMSATS Institute of Information Technology 11


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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 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

COMSATS Institute of Information Technology 12


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Name Size Bytes Class

X 1x8193 65544 double array Grand total is 8193


elements usainrrayg 655 44 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 Task:
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.

1. Signals in MATLAB Output:

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 Output:
termed as analog. In this lab, we will mostly be
dealing with discrete time signals.

MATLAB representation

In MATLAB, signals are represented by using two


variables i.e. y=sin (t) where variable‘t’ represents >> t=0:0.01:7;
the time axis and ‘y’ represents the signal values.
>> y=sin(t);
1.2. Digital signals
>> plot(y)

If both independent (Time) or dependent (Signal


values) variables are discrete, the signal is termed as digital. Digital signals uses discrete or
discontinuous values to represent information.

MATLAB representation:
>> n=0:7;

COMSATS Institute of Information Technology 13 >> y=sin(n);

>> stem(n,y)
Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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

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 discretetime
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

COMSATS Institute of Information Technology 14


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

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).

Code:
n = -10:9;

x = zeros(1,length(n));

i = find(n==0)

stem (n,x)

n0 = 1

if n0<0

new_i = i + n0;

x(new_i)=1

elseif n0>0

new_i = i + n0;

x(new_i) = 1

else

x(i) = 1

end

stem(n,x)

Figure:

COMSATS Institute of Information Technology 15


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

In-Lab Tasks:

Task 01:

Generate a Continuous time cosine signal and plot it.

Code:
% Generate a Continuous time cosine signal and plot it.

t = -6:0.01:6;

y = cos(t);

plot(t,y,'b','LineWidth',2);

title 'Continuous time cosine signal';

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

COMSATS Institute of Information Technology 16


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 02:

Generate a Discrete time exponential signal and plot it.

Code:
% Generate a Discrete time exponential signal and plot it.

t = -6:0.5:6;

y = exp(t);

stem(t,y,'b','LineWidth',2)

title 'Discrete time exponential signal';

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

COMSATS Institute of Information Technology 17


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 03:Write a MATLAB program for the ‘running average’, 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: >> y=running_average(x) where x is the
input signal, and y is the running total of that signal.

Code:
% Task 03

x = 1:100;

y = x(1);

for i = 2:100;

y(i) = (x(i))+(y(i-1))

end

Output:

COMSATS Institute of Information Technology 18


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 04:

Write a program to compute the variance and mean of a signal x. The variance σ is

defined to be:
N
1
σ = ∑ (x i− x́ )
N i=1

where ‘ x́ ’ is the mean value of the signal x. For signal x, use all the integers from 1
to 1000.

Code:
% Task 04

clear

close all

clc

x = 1:1000;

COMSATS Institute of Information Technology 19


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

x1 = mean(x)

for i=1:1000;

x(i) = x(i)-x1;

end

A = x(i)

var = A/1000

Output:

x1 = 500.5000 A = 499.5000

var = 0.4995

Task 05:

Can you explain what the following program does:

L = length(x);

for i = 1: L

if x (i) < 0

x (i) = -1;

end

end

COMSATS Institute of Information Technology 20


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Answer:

The following program replaces every element of the vector x which is 0 with -1.

The given program does the following functionality;

 Statement 1 gives the length of the vector x and then stores it in the variable L.
 Then for loop is called and it runs L times. Value of variable i starts from 1 to the
variable L.
 Then if statement is used which checks whether a certain element of the vector x is
less than 0 or not.
 The fourth line replaces the value of x with -1 whose value is zero and it runs when the
preceding if statement is true.

Task 06:

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].

Code:
n=-10:1:10;
y=(n>=0);
y2=(n>=1);
z=y-y2;
figure(1)
stem(n,y)
figure(2)
stem(n,y2)
figure(3)
stem(n,z)

COMSATS Institute of Information Technology 21


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 07:

Generate an impulse sequence δ [n] as described in In-Lab section, use it to generate


a step sequence

u [ n ] =∑ σ [n−k ]
k

Code:
n = -10:10;

a = zeros(1,length(n));

k = 10;

c = 0;

for i = 0:k

b = impulse(-10,10,i)

c = c+b;

end

y = a+c

stem(n,y,'b','LineWidth',2)

function a = impulse(x1,x2,x0)

COMSATS Institute of Information Technology 22


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

x = x1:x2

a = zeros(1,length(x))

for i=1:length(x)

if x(i)==0

b = i

end

end

a(b+x0)=1

stem (x,a,'b','LineWidth',2)

end

Figure:

COMSATS Institute of Information Technology 23


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 08:

Generate the following sequences using step and impulse sequence.

a. x[n] = u[n] – u[n-10]

Code:

close all

clear all

clc

t=-15:1:15;

x= heaviside(t);

subplot(3,1,1)

stem(t,x)

x1=heaviside(t-10)

subplot(3,1,2)

stem(t,x1)

z= x-x1;

subplot(3,1,3)

stem(t,z)

COMSATS Institute of Information Technology 24


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

b. x[n] = an u[n]

Code:

close all

clear all

clc

t = -5:1:20;

x = ((4/5).^t).*heaviside(t);

stem(t,x);

Figure:

COMSATS Institute of Information Technology 25


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

c. ∑ anδ[n-k] , k = -10 to 10

Code:
clc
clear all
close all
a=5
k=-10:10
n=-10:10
imp=((n-k)==0)
x=a.^n.*imp
y=sum(x)

Figure:

COMSATS Institute of Information Technology 26


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Conclusion:
This lab was the introductory lab of discrete time signal. In this lab we learned about the basic
concepts like Conditional Statements and Loops, Plotting, Programming in
MATLAB (M-File), Some fundamentals sequences: Impulse Sequence, Step Sequence.
Also I generated some sinusoidal and exponential signals and observe the changes on signals on
changing frequency and amplitude. By increasing the frequency, the Time period decreases and
cycles increase. Also calculate the running average, sum variance and mean of numbers on
MATLAB. Also generates step sequence and impulse sequence of discrete time signal.

EEE324 Digital Signal Processing


COMSATS Institute of Information Technology 27
Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Lab # 02: Basic Operations on Discrete-Time

Sequences

Name Abdul basit

Registration Number FA18-BEE-002

Class BEE-6A

Instructor’s Name Ma’am Nida Zamir

Lab Assessment

Post Lab Total


Pre-Lab In-Lab Data
Data Analysis Writing Style
Presentation

Details of Group Members


Abdul Basit FA18-BEE-002

Hareem Safdar FA18-BEE-048

COMSATS Institute of Information Technology 28


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Lab # 02 Basic Operations on Discrete-Time Sequences


Objective:
By the end of this lab students will be able to perform signal shifting and folding operations in
Matlab, in addition students will be able to perform arithmetic operations like adding, subtracting
or multiplying signals of different lengths.

Pre-Lab:
a. How to write script in M-file
i. Click on File drop down menu and go to New tab and select Script/M-file

or just write following in Command Window to open the M-file

>> script

ii. Once the mfile is open write your code and then save it by some name as

COMSATS Institute of Information Technology 29


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

iii. After writing the code click the play button on the m-file window to run the
code

b. How to make a function in Matlab

A function in Matlab is similar to a function in C/C++. Once a function is made it can be called in
any other function/script just like C/C++. Note that script is just a code but function is more like a
separate object or entity. Just like C/C++ there is a particular syntax for making a function as given
below.

i. function command is used to define a function as

function [output1 output2 output3] = func_name(input1 input2 input3)

Code

..

end

ii. Each function is defined in a separate M-file iii. Each function has a distinct name
and file is also saved with the same name as function. If an M-file having the function
with a name “average” is saved by the name of “avg”, then this function cannot be
called in another file.

COMSATS Institute of Information Technology 30


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

c. How to call a functions in Matlab

i. In order to call a function in another file the directory of both file must be same. ii.
Before calling the function inputs needs to be defined in the script or command window.

iii. Suppose we have a function by the name of “average” that takes the average of three
numbers n1, n2 and n3 and returns average avg, then following code must be written in
command window or script to call this function
n1 = 10; % defined n1 n2

= -5; % defined n2 n3 =

20; % defined n3

[avg] = average (n1, n2, n3); % function called

or simply,

[avg] = average (10,-5, 20); % function called directly

iv. If the inputs are not defined the function call will produce an error and also function
cannot be run using the play button in m-file unlike scripts.

d. Some relevant MATLAB commands to generate different


type of signals (See help of following)

COMSATS Institute of Information Technology 31


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

e. Generating a signal in Matlab

A signal x[n] in Matlab in matlab is defined using two arrays or sequences, one array representing
the magnitudes “x” and the other array defining the time indexes i.e. the signal given in the figure
(on right side) will be defined as

>> n = 0:4;

>> x = [6, 11, 14, 5, 0]

It is of particular importance to mention that any operation performed on this signal i.e. shifting,
folding etc. will be performed on both the magnitudes “x” and time index “n”.

f. Some other type of signals

1. Real-valued exponential Sequence


The operator “.^” is required to implement a real exponential sequence. For example, to
generate x(n) = (0.9)n, 0<= n<=10, we will need the following script:
Example tutorial:

>> n = [0:10];

>> x = (0.9).^n;

Create a function (M-file) to generate an exponential sequence. Use the previous


examples as your guide.

2. Complex-valued exponential Sequence

A matlab function “exp” is used to generate exponential sequences. For example, to


generate x(n) = exp[(2+j3)n], 0<= n<=10, we will need the following script:

>> n = [0:10];

>> x = exp((2+3j)*n);

Note that you need different plot commands for plotting real and imaginary components.

COMSATS Institute of Information Technology 32


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

3. Sinusoidal sequence

A matlab function “cos” (or sin) is used to generate sinusoidal sequences.

To generate x(n) = 3cos(0.1πn + π/3) + 2sin(0.5 πn), 0<= n<=10, we will need the
following script:

>> n = [0:10];

>> x = 3*cos(0.1*pi*n+pi/3) + 2*sin(0.5*pi*n);

4. Random Sequences

A random or stochastic sequences are characterised by parameters of the associated


probability density functions or their statistical moments. In matlab, 2 types of (psuedo )
random sequences are avalable: “rand(1,N)” generates a length N random sequence whos
elements are uniformly distributed between 0 and 1. “randn(1,N) generates a length N
gaussian random sequence with mean 0 and variance 1. Other random sequences can be
generated suing transformation of the above functions. (Check previous lecture slides)

5. Periodic sequence

A sequence is periodic if x(n) = x(n +N). To generate P periods of x(n) from one period, we
can copy x(n) P times:

>> xtilde = [x,x,x,x...,x];

An elegant approach is to use matlab’s indexing capabilites:

Generate a matrix containing P rows of x(n) values. Concatenate P rows into a long row
vector using the construct (:).

Have to use matrix transposition operator (‘) to provide the same effect on rows:

>> xtilde = x' * ones(1,P); %P columns of x; x is a row vector

>> xtilde = xtilde(:); %long coloumn vector

>> xtilde = xtilde'; %long row vector

In-Lab

Important Signal Operations in Matlab:

1. Signal Scaling Description:

In this Operation each sample is multiplied by a scalar. Use the command “*” for scaling.

COMSATS Institute of Information Technology 33


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

2. Signal Shifting

Description: During a shift operation a signal changes its position in time where each sample of
x(n) is shifted by an amount k to obtain a shifted sequence y[n].

y n( ) { (x n k)}

In Matlab, this operation is not so simple, both “x” and “n” need to be processed separately in order
to get the shifted signal x[n-k]. Perform following steps to in Matlab to perform the signal shift.

i) Check whether k is positive or negative? ii) If k is positive it means shift is towards


right i.e. x[n-k] then do following

a. As signal is shifting towards right time axes “n” should be extended towards right side by
“k” samples i.e. if n is ending at n2 then it should now end at n2 + k.
b. Since the signal has now moved towards right meaning initial “k” samples in

“x” are empty so concatenate “k” zeroes in the beggining of the sequence x.

iii) If k is negative it means shift is towards left i.e. x[n+k] then do following

c. As signal is shifting towards left time axes “n” should be extended towards left side
by “k” samples i.e. if n is starting at n1 then it should now start at n1 - k.
d. Since the signal has now moved towards left meaning last “k” samples in “x” are
empty so concatenate “k” zeroes in the end of the sequence x.

3. Folding

Description: Folding operation is also termed as flipping a signal where each sample is of x(n) is
mirrored around n=0 to obtain a folded sequence y(n) = x[-n].

In Matlab, folding operation can be performed in three steps

i) Flip the magnitude sequence “x” ii) Flip the


time index “n”

iii) Now multiply the flipped time vector “n” with a minus

Note that in Matlab a built-in function “fliplr(m) can be used to flip any sequence.

4. Add/Subtract/Multiply two signals

Adding a signal in Matlab is not as easy as on paper. In order to add two sequences x1 and x2 in
Matlab, both sequences have to be of same length, same is the case for subtraction, multiplication
and division.

COMSATS Institute of Information Technology 34


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

In signal processing signal elements are added/subtracted or multiplied corresponding to their time
index i.e. a signal element at time -1 will be added to the signal element of the other signal at the
same time.

We know that signals can have different starting and ending times, here we want to modify time
indexes such that both signals start from the lowest time index and end at highest time index and
accordingly concatenate zeros or at the start or end of the signal. Suppose we want to add/multiply
two signals x1[n] specified by x1 and n1 in Matlab and and x2[n] specified by x2 and n2 in
Matlab. Following two steps can be followed to make the lengths of x1 & x2 and making n1 and
n2 same as well.

a. Compare the starting points of both signals time index vectors i.e. n1(1) and n2(1).

If n1(1) is smaller than n2(1)

 Concatenate n2(1) – n1(1) number of zeros before x2


 And put n2(1) = n1(1);

Else-If n2(1) is smaller than n1(1)

 Concatenate n1(1) – n2(1) number of zeros before x1


 And put n1(1) = n2(1);
b. Compare the ending points of both signals time index vectors i.e. n1(end) and n2(end).

If n1(end) is greater than n2(end)

 Concatenate n1(end) – n2(end) number of zeros at the end of x2


 And put n2(end) = n1(end);

Else-If n2(end) is greater than n1(end)

 Concatenate n2(end) – n1(end) number of zeros at the end of x1


 And put n1(1) = n2(1);
c. Now make a universal time index n = n1(1):n2(1)
d. Add the magnitude vectors by as x = x1+x2 or multiply them as x = x1.*x2 etc.

In-Lab Tasks:

Task 01:

COMSATS Institute of Information Technology 35


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Take an exponential signal and perform scaling operation with a negative integer as
given in In-Lab Work section and plot the result.

Code:
n = -6:6;

% Exponential Signal

x = exp(n);

% Scaled Exponential Signal

x_scaled = -1*exp(n); % Scaling by using "*" command.

% For plotting "Exponential Signal"

subplot(2,1,1);

stem(n, x, 'b', 'LineWidth', 2);

title 'Exponential plot of x = exp(n)'

xlabel 'Time --->';

ylabel 'Amplitude --->';

% For plotting "Scaled Exponential Signal"

subplot(2,1,2);

stem(n, x_scaled, 'b', 'LineWidth', 2);

title 'Exponential plot of x = -1*exp(n)'

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

COMSATS Institute of Information Technology 36


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 02:

Write a Matlab function “sigshift” for producing a delay of ‘k’ in a given sequence
‘x[n]’ defined by arrays “x” and “n” by using the pseudo code given in In-Lab Work
section. Your function should yield y[n] = x[n-k].

function [y,n]=sigshift(x,n,k)

Code:

COMSATS Institute of Information Technology 37


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

n = -5:5;

k1 = 3;

[y1,n1] = sigshift(x,n,k1);

% For plotting "Ramp Signal"

subplot(2,1,1);

stem(n, x, 'b', 'LineWidth', 2);

title 'Ramp signal'

xlabel 'Time --->';

ylabel 'Amplitude --->';

axis ([-9 9 0 10])

% For plotting "Shifted Ramp Signal"

subplot(2,1,2);

stem(n1, y1, 'b', 'LineWidth', 2);

title 'Ramp signal Shifted by factor of -3'

xlabel 'Time --->';

ylabel 'Amplitude --->';

axis ([-9 9 0 10])

% Defining the Function (sigshift):

function [y,n] = sigshift(x,n,k)

z1 = zeros(1,k);

if k>0

n = n(1):n(end)+k;

y = horzcat(z1,x);

elseif k<0

n = n(1):n(end)+k;

COMSATS Institute of Information Technology 38


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

y = horzcat(x,z1);

end

end

Figure:

Task 03:

Write a Matlab function “sigfold” for folding a given sequence ‘x[n]’ defined by
arrays “x” and “n” by using the pseudo code given in In-Lab Work section.

function [y,n]=sigfold(x,n)

Code:

Function:
function [y,n] = sigfold(x,n)
y = fliplr(x);
end

code:
n = -5:5;
x = (n==3);

COMSATS Institute of Information Technology 39


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

[y,n1] = sigfold(x,n);

subplot(1,2,1);
stem(n,x,'linewidth',2);

subplot(1,2,2);
stem(n1, y,'linewidth',2);

Figure:

Task 04:

Write a Matlab function “sigadd” for adding two sequences x1[n] and x2[n] by using
the pseudo code given in In-Lab Work section.

function [y,n]=sigadd(x1,n1,x2,n2)

Code:
n1 = 1:7;

n2 = 1:4;

x1 = ones(1,7);

x2 = ones(1,4);

COMSATS Institute of Information Technology 40


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

[y, n] = sigadd(x1,n1,x2,n2);

% For plotting Sequence x1[n1]:

subplot(2,2,1);

stem(n1, x1, 'b', 'LineWidth', 2);

title 'Step function x1[n1]'

xlabel 'Time --->';

ylabel 'Amplitude --->';

axis ([0 8 0 1.5]);

% For plotting Sequence x2[n2]:

subplot(2,2,2);

stem(n2, x2, 'b', 'LineWidth', 2);

title 'Step function x2[n2]'

xlabel 'Time --->';

ylabel 'Amplitude --->';

axis ([0 6 0 1.5]);

% For plotting the new Sequence that comes by adding x1[n] and x2[n]:

subplot(2,2,[3 4]);

stem(n, y, 'b', 'LineWidth', 2);

title 'Addition of x1[n1] and x2[n2]'

xlabel 'Time --->';

ylabel 'Amplitude --->';

axis ([0 8 0 2.5]);

% Defining the function [y,n] by sigadd command:

function [y,n] = sigadd(x1,n1,x2,n2)

if n1(1)<n2(1)

z1 = zeros(1,n2(1)-n1(1));

COMSATS Institute of Information Technology 41


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

x2 = horzcat(z1,x2);

n2(1) = n1(1);

elseif n2(1)<n1(1)

z1 = zeros(1,n1(1)-n2(1));

x1 = horzcat(z1,x1);

n1(1) = n2(1);

end

if n2(end)<n1(end)

z2 = zeros(1,n1(end)-n2(end));

x2 = horzcat(x2,z2);

n2(end) = n1(end);

elseif n1(end)<n2(end)

z2 = zeros(1,n2(end)-n1(end));

x1 = horzcat(x2,z2);

n1(end) = n2(end);

end

n = n1(1):n2(end);

y = x1 + x2;

end

Figure:

COMSATS Institute of Information Technology 42


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 05:

Let x ( n )={1 , 2 ,3 , 4 , 5 ,6,7 , 6 , 5 , 4 ,3 , 2 ,1 }

Determine and plot the following sequences

a. x 1=2 x ( n−5 )−3 x (n+ 4)


b. x 2=x ( 3−n ) + x (n) x( n−2)

x 1=2 x ( n−5 )−3 x (n+ 4)

Code:
x = [1 2 3 4 5 6 7 6 5 4 3 2 1];
b=length(x);
n = 1:b+5;
y=[0 0 0 0 0];
x1 = 2*[y x];
x2 = 3*[x y];
x3 = x1-x2;
subplot(1,2,1)
stem(n-5, x3,'linewidth',2);

COMSATS Institute of Information Technology 43


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Figure:

x 2=x ( 3−n ) + x (n) x( n−2)

Code:
x = [1 2 3 4 5 6 7 6 5 4 3 2 1];
b=length(x);
n = 1:b+3;
x1 =[0 0 0 x];
x2 = [0 0 x];
x3 = [x 0 0];
x4 =x2.*x3;
maxlength =max([length(x1),length(x4)]);
x1(length(x1)+1:maxlength) =0;
x4(length(x4)+1:maxlength) =0;
x5 = x1+x4;
subplot(1,2,2)
stem(n-3, x5,'linewidth',2);

COMSATS Institute of Information Technology 44


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Figure:

Conclusion:
In this particular lab we had learnt to perform signal shifting and folding operations in Matlab, in
addition I was able to perform arithmetic operations like adding, subtracting or multiplying signals
of different lengths. Analysis have been performed on discrete time signals. The changes due to
signal processing and manipulation have been also being observed. Signal scaling done in the lab
scales the value of amplitude of the signal, shifting done on signals results in the signal being either
delayed or advanced along the x-axis. Folding a signal mirrors, it about both the x, and y axes.
Addition, Multiplication and Subtraction is done using user created functions.

EEE324 Digital Signal Processing

COMSATS Institute of Information Technology 45


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Lab # 03 Convolution of Discrete-Time Sequences

Name Abdul basit

Registration Number FA18-BEE-002

Class BEE-6A

Instructor’s Name Ma’am Nida Zamir

Lab Assessment

Post Lab Total


Pre-Lab In-Lab Data
Data Analysis Writing Style
Presentation

Details of Group Members


Abdul Basit FA18-BEE-002

Hareem Safdar FA18-BEE-048

COMSATS Institute of Information Technology 46


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Lab # 03 Convolution of Discrete-Time Sequences

Objective:
By the end of this lab students will be able to get output from LTI systems by convolving input
x(n) with impulse response h(n). This will add to their understanding of LTI system and its
operation.

Pre Lab Work:


Before performing convolution, you should be familiar with the basic operations on continuous
time signals.

1. Time Reversal y(t) = x(-t) 2. Time Shifting y(t) = x(t-td) 3. Amplitude Scaling
y(t) = Bx(t) 4. Addition y(t) = x1(t) + x2(t) 5. Multiplication y(t) = x1(t)x2(t)
6. Time Scaling y(t) = x(at)

7. Decomposition of signals:

Lets have a look at how to decompose a signal into its even and odd components Even

and odd synthesis

if xe ( n) xe (n)
if xo ( n) xo (n)
then xe (n)is called even(symmetric) then xo (n)is called odd(antisymmetric)

Any arbitrary real-valued sequence x(n) can be decomposed into its even and odd component

x(n) xe (n) xo (n)

xe (n) 12[x(n) x( n)], xo (n) 12[x(n) x( n)]

Try writing a function that decomposes a given signal into its even and odd components.
You can think like the steps given below.
 Input a signal
 Flip the signal
 Calculate its length
 Zero padding
 Calculating even and odd parts.

Recall the “conv” command you used in your signals and systems course. Try performing
convolution using conv command. >> y = conv(x,h)

COMSATS Institute of Information Technology 47


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

You will see there is a limitation in conv command. Can you find a solution to it?

In-Lab Work : There are two widely used methods to compute convolution. We will discuss both
methods before performing Lab tasks.

Method 1:

Convolution as sum of shifted and scaled impulse response:

• For any given n, one point convolution is evaluated as

– Step 1: time reversal of either signal (e.g., x(k) x(-k) ) or h(k) h(-k)

– Step 2: shift h(-k) by n samples to obtain h(n-k)

– Step 3: multiply x(k) and h(n-k) for each k and then take the summation over k

Note

• You need to change variable n to get the whole sequence

Example:

x(n)=[1 2 3 4] and h(n)=[1 –1]

Step 1: Time reversal


h(k)=[1 -1] h(n-

COMSATS Institute of Information Technology Page 39

COMSATS Institute of Information Technology 48


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Step 2: Time shift

Step 3: Multiply and Add

Final Result:

COMSATS Institute of Information Technology 49


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

x(n)

Method 2:

Convolution as sum of shifted and scaled unit impulses. Y(n) = ∑k x(n)h(n-k) x(n) = ∑k ak δ(n-k)

y(n)= ∑k (∑k ak δ(n-k)) h(n-k) y(n)= ∑ (a0 δ(n)+ a1 δ(n-1)+ a2 δ(n-2)+ a3 δ(n-3)+ …….. ) h(n-k)

y(n)= ∑ a0 δ(n) h(n)+ ∑a1 δ(n-1) h(n-1)+ ∑ a2 δ(n-2) h(n-2)+ ∑a3 δ(n-3) h(n-3)+ ……..

Example:

Consider the same example we solved in first method of convolution as above. X(n) = [1

2 3 4], h(n)= [1 -1] y(n)= ∑ (a0 δ(n) h(n)+ a1 δ(n-1) h(n-1)+ a2 δ(n-2) h(n-2)+ a3 δ(n-3)

h(n-3)

δ(n-3) h(n- Y3
4
1 2) 4

X 3 =4 2 3
-1 -4
3 nnn

Final Result:

Final result is the summation of y0, y1,y2, y3.

y(n)

1111

COMSATS Institute of Information Technology 50


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

0 1 2 3 4 n

-4

In Lab Tasks:
Task 1:

Write a Matlab code to decompose a sequence into its even and odd components. Take help from
Pre-Lab work.

Code:

n = 0:0.000001:10;

x = sin(n)+cos(n);

x1 = sin(-n)+cos(-n);

xE = (1/2).*(x + x1);

xO = (1/2).*(x - x1);

subplot(3,1,1);

plot(n, x, 'b', 'LineWidth', 2);

title 'Original'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(3,1,2);

plot(n, xE, 'r', 'LineWidth', 2);

title 'Even signal'

COMSATS Institute of Information Technology 51


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(3,1,3);

plot(n, xO, 'g', 'LineWidth', 2);

title 'Odd Signal'

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

Task 2:

You should have noticed that ‘conv’ command calculates convolution assuming both input
sequences are starting from origin (i-e no values on –ve t-axis). This is not always the case, we do

COMSATS Institute of Information Technology 52


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

have sequences which have values for t<0. Write a code conv_m that would remove this limitation
in the code conv.

Code:

Conv_m code:

function [Y,n] = conv_m(x,n1,h,n2)

m=length(x);

n=length(h);

X=[x,zeros(1,n)];

H=[h,zeros(1,m)];

%i2=1:n+m-1;

for i=1:n+m-1

Y(i)=0;

for j=1:m

if(i-j+1>0)

Y(i)=Y(i)+X(j)*H(i-j+1);

else

end

end

end

main code:

n1 = 0:3;

n2 = [-1 0];

h = [1 -1];

x = [0 1 2 3];

[Y,n] = conv_m(x,n1,h,n2);

subplot(2,2,1);

stem(n1,x,'k','LineWidth',2);

COMSATS Institute of Information Technology 53


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

title 'Input signal'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(2,2,2);

stem(n2,h,'g','LineWidth',2);

title 'Impulse response signal'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(2,2,3);

stem(Y,'r','LineWidth',2);

title 'Convoluted signal'

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

Task 3: Convolve following sequences using MATLAB Function “conv” and “conv_m” and plot
the input, impulse response and output in one figure using “subplot”:

x[n] = [1 2 1], n=[0 1 2] h[n] = [1 1 1], n= [0 1 2] x[n] =


[-1 4 -3 -2 1 0 2], n=[-2:4] h[n] = [1 1 1], n= [-1 0 1]

COMSATS Institute of Information Technology 54


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Code:

n1= 0:4;

x1 = [1 2 1];

nx1 = [0 1 2];

h1 = [1 1 1];

nh1 = [0 1 2];

Y1= conv(x1,h1);

[Y,n] = conv_m(x1,nx1,h1,nh1);

n2=0:4;

x2 = [-1 4 -3];

nx2 = [0 1 2];

h2 = [1 1 1];

nh2 = [0 1 2];

Y3= conv(x2,h2);

[Y2,n] = conv_m(x2,nx2,h2,nh2);

subplot(4,2,1);

stem(nx1, x1, 'b', 'LineWidth', 2);

title 'In_1'

xlabel 'Time -->';

ylabel 'Amplitude -->';

subplot(4,2,2);

stem(nh1, h1 , 'b', 'LineWidth', 2);

title 'I-R 1'

xlabel 'Time --->';

ylabel 'Amplitude --->';

COMSATS Institute of Information Technology 55


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

subplot(4,2,3);

stem(nx2, x2, 'b', 'LineWidth', 2);

title 'In_2'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(4,2,4);

stem(nh2, h2, 'b', 'LineWidth', 2);

title 'I-R 2'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(4,2,5);

stem(n1, Y1, 'y', 'LineWidth', 2);

title 'Conv_1'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(4,2,6);

stem(n1,Y, 'y', 'LineWidth', 2);

title 'Conv_1'

xlabel 'Time --->';

ylabel 'Amplitude --->';

subplot(4,2,7);stem(n2,Y3, 'y', 'LineWidth', 2); title 'Conv_2' xlabel 'Time


--->';

ylabel 'Amplitude --->';

COMSATS Institute of Information Technology 56


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

subplot(4,2,8);

stem(n2,Y3, 'y', 'LineWidth', 2);

title 'Conv_2'

xlabel 'Time --->';

ylabel 'Amplitude --->';

Figure:

COMSATS Institute of Information Technology 57


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Task 4: Write a function convolution in MATLAB that performs 1D linear convolution by the
steps mentioned above. You can use any method.

Sigadd:
function [y,n] = sigadd(x1,n1,x2,n2)

if n1(1)<n2(1)
z1 = zeros(1,n2(1)-n1(1));
x2 = horzcat(z1,x2);
n2(1) = n1(1);
elseif n2(1)<n1(1)
z1 = zeros(1,n1(1)-n2(1));
x1 = horzcat(z1,x1);
n1(1) = n2(1);
end

if n2(end)<n1(end)
z2 = zeros(1,n1(end)-n2(end));
x2 = horzcat(x2,z2);
n2(end) = n1(end);
elseif n1(end)<n2(end)
z2 = zeros(1,n2(end)-n1(end));
x1 = horzcat(x2,z2);
n1(end) = n2(end);
end

n = n1(1):n2(end);
y = x1 + x2;
end

Sigfold:
function [y,n] = sigfold(x,n)
y = -fliplr(x);
end

Sigmulti:

COMSATS Institute of Information Technology 58


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

function [y,n] = sigmulti(x1,n1,x2,n2)


if n1(1)<n2(1)
z1 = zeros(1,n2(1)-n1(1));
x2 = horzcat(z1,x2);
n2(1) = n1(1);
elseif n2(1)<n1(1)
z1 = zeros(1,n1(1)-n2(1));
x1 = horzcat(z1,x1);
n1(1) = n2(1);
end
if n2(end)<n1(end)
z2 = zeros(1,n1(end)-n2(end));
x2 = horzcat(x2,z2);
n2(end) = n1(end);
elseif n1(end)<n2(end)
z2 = zeros(1,n2(end)-n1(end));
x1 = horzcat(x1,z2);
n1(1) = n2(1);
end
n = n1(1):n2(end);
y = x1.*x2;
end

Sigshift:
function [y,n] = sigshift(x,n,k)

z1 = zeros(1,k);
if k>0
n = n(1):n(end)+k;
y = horzcat(z1,x);

elseif k<0
n = n(1):n(end)+k;
y = horzcat(x,z1);

end

Sigsub:
function [y,n] = sigsub(x1,n1,x2,n2)
if n1(1)<n2(1)
z1 = zeros(1,n2(1)-n1(1));
x2 = horzcat(z1,x2);
n2(1) = n1(1);
elseif n2(1)<n1(1)
z1 = zeros(1,n1(1)-n2(1));
x1 = horzcat(z1,x1);
n1(1) = n2(1);
end
if n2(end)<n1(end)
z2 = zeros(1,n1(end)-n2(end));
x2 = horzcat(x2,z2);
n2(end) = n1(end);
elseif n1(end)<n2(end)
z2 = zeros(1,n2(end)-n1(end));
x1 = horzcat(x1,z2);
n1(1) = n2(1);

COMSATS Institute of Information Technology 59


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

end
n = n1(1):n2(end);
y = x1 - x2;
end

Main code:

function [ S,time ] = task4( x1,n1,x2,n2 )


%CONVOLVE Summary of this function goes here
% Detailed explanation goes here
l1=length(x1);
l2=length(x2);
z1=zeros(1,abs(n1));
z2=zeros(1,abs(n2));
figure(1)
if(n1<0)
t1=n1:1:l1-1-abs(n1);
subplot(221)
stem(t1,x1)
title('original signal')
x1=[z1 x1];
t0=n1:1:l1-1;
subplot(223)
stem(t0,x1);
title('signal shifted at origin')
else
t1=n1:1:l1-1+abs(n1);
subplot(221)
stem(t1,x1)
title('original signal')
x1=[x1 z1];
t0=0:1:l1-1+abs(n1);
subplot(223)
stem(t0,x1);
title('signal shifted at origin')
end
if(n2<0)
T1=n2:1:l2-1-abs(n2);
subplot(222)
stem(T1,x2)
title('original signal')
x2=[z2 x2];
T0=n2:1:l2-1;
subplot(224)
stem(T0,x2);
title('signal shifted at origin')

COMSATS Institute of Information Technology 60


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

else
T1=n2:1:l2-1+abs(n2);
subplot(222)
stem(T1,x2)
title('original signal')
x2=[x2 z2];
T0=0:1:l2-1+abs(n2);
subplot(224)
stem(T0,x2);
title('signal shifted at origin')
end
y=conv(x2,x1);
Tc=t0(1)+T0(1):t0(end)+T0(end);
figure(2)
stem(Tc,y)
title('Convolution by using built in command')

len=length(x1)-length(x2);
ze=zeros(1,abs(len));
if(len>0)
x2=[x2 ze];
else
x1=[x1 ze];
end

L1=length(x1);
L2=length(x2);
Z1=zeros(1,L1-1);
X1=[Z1 x1];
X1=fliplr(X1);
X2=[Z1 x1];
a=[0];
for i=1:1:length(X1)+length(x2)+1
A=X1.*X2;
S(i)=sum(A);
X1=[a X1];
X1(end)=[];

end
figure(3)
time=0:1:length(S)-1;
stem(time,S)
title('Convolution without using built in command')

end

x1 = [3 2 1]
n1 = 3
x2 = [3 2 1]
n2 = 2
[ S,time ] = task4( x1,n1,x2,n2 )

COMSATS Institute of Information Technology 61


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

Figure:

Critical Analysis and Conclusion: (By Student about


Learning from the Lab)

In this lab we had learnt about Convolution. Convolution is a mathematical way of combining two
signals to form a third signal. It is the single most important technique in Digital Signal
Processing. Using the strategy of impulse decomposition, systems are described by a signal called
the impulse response. The tools used in a graphical method of finding convolution of discrete time
signals are basically plotting, shifting, folding, multiplication and addition. These are taken in the
order in the graphs.

COMSATS Institute of Information Technology 62


Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB

The End

COMSATS Institute of Information Technology 63

You might also like