DSP Lab 1 - 03
DSP Lab 1 - 03
Class BEE-6A
Lab Assessment
Post Lab Total
Pre-Lab In-Lab Data
Data Analysis Writing Style
Presentation
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.
at the MATLAB prompt. This short introduction will demonstrate some basic MATLAB
commands.
>> help
help ops
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;
-13.2388
Note the semicolon after each variable assignment. If you omit the semicolon, then MATLAB
echoes back on the screen the variable value.
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
e.g.,str1=’DSP’;
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
You can also define the imaginary number with any other variables you like. Try the following:
>> z = 3+4*img
>> exp(pi*img)
+ addition
− subtraction
* multiplication
There are also three other operators that operate on an element by element basis:
Suppose that we have the vectors x = [x 1, x2, ..., xn] and y = [y1, y2, ..., yn]. Then x. y =
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]
To compute the dot product of two vectors, you can use the multiplication operator *. For the
above example, it is:
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.
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]
>> 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
>> jj= 2 : 4 : 17
>> jj=20 : -2 : 0
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(3:7)
>> x(2:2:length(x)
You can allocate memory for one-dimensional arrays (vectors) using the zeros command. The
following command allocates memory for a 100-dimensional array:
Similarly, you can allocate memory for two-dimensional arrays (matrices). The command
defines a 4 by 5 matrix. Similar to the zeros command, you can use the command ones to define a
vector containing all ones,
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.
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
WHILE:
x=-10; while
x<0 x=x+1;
end
FOR loop:
X=0; for i =
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
Meaning Symbol
Equal ==
Not equal ˜=
AND &
OR |
NOT ˜
Write a code that prints 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;
18
16
14
12
10
0
0 2 4 6 8 10 12 14 16 18 20
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:
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:
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:
% the average of x
Remarks:
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:
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:
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:
Note that MATLAB’s data files have the extension .mat. To retrieve the data that was saved in the
vector x, type:
The vector x is loaded in memory. To see the contents of memory use the command whos:
>> whos
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.
MATLAB representation
MATLAB representation:
>> n=0:7;
>> stem(n,y)
Lab # 01 Introduction to Discrete Time Signal Processing on MATLAB
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.
Find the index when ‘n’ is equal to the 0, and save its value into a variable ‘i’.
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.
Find the index when ‘n’ is equal to the 0, and save its value into a variable ‘i’.
Replace ‘0’s by ‘1’s in an array ‘x’ starting from the index ‘i + n0’ upto the last
index of the array.
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).
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:
In-Lab Tasks:
Task 01:
Code:
% Generate a Continuous time cosine signal and plot it.
t = -6:0.01:6;
y = cos(t);
plot(t,y,'b','LineWidth',2);
Figure:
Task 02:
Code:
% Generate a Discrete time exponential signal and plot it.
t = -6:0.5:6;
y = exp(t);
stem(t,y,'b','LineWidth',2)
Figure:
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:
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;
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:
L = length(x);
for i = 1: L
if x (i) < 0
x (i) = -1;
end
end
Answer:
The following program replaces every element of the vector x which is 0 with -1.
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:
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)
Task 07:
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)
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:
Task 08:
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)
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:
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:
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.
Sequences
Class BEE-6A
Lab Assessment
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
>> script
ii. Once the mfile is open write your code and then save it by some name as
iii. After writing the code click the play button on the m-file window to run the
code
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.
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.
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
or simply,
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.
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;
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”.
>> n = [0:10];
>> x = (0.9).^n;
>> n = [0:10];
>> x = exp((2+3j)*n);
Note that you need different plot commands for plotting real and imaginary components.
3. Sinusoidal sequence
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];
4. Random Sequences
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:
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:
In-Lab
In this Operation each sample is multiplied by a scalar. Use the command “*” for scaling.
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.
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].
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.
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.
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).
In-Lab Tasks:
Task 01:
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);
subplot(2,1,1);
subplot(2,1,2);
Figure:
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:
n = -5:5;
k1 = 3;
[y1,n1] = sigshift(x,n,k1);
subplot(2,1,1);
subplot(2,1,2);
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
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);
[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);
[y, n] = sigadd(x1,n1,x2,n2);
subplot(2,2,1);
subplot(2,2,2);
% For plotting the new Sequence that comes by adding x1[n] and x2[n]:
subplot(2,2,[3 4]);
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
Figure:
Task 05:
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);
Figure:
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);
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.
Class BEE-6A
Lab Assessment
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.
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
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
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)
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:
– Step 1: time reversal of either signal (e.g., x(k) x(-k) ) or h(k) h(-k)
– Step 3: multiply x(k) and h(n-k) for each k and then take the summation over k
Note
Example:
Final Result:
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:
y(n)
1111
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);
title 'Original'
subplot(3,1,2);
subplot(3,1,3);
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
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:
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);
subplot(2,2,2);
stem(n2,h,'g','LineWidth',2);
subplot(2,2,3);
stem(Y,'r','LineWidth',2);
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”:
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);
title 'In_1'
subplot(4,2,2);
subplot(4,2,3);
title 'In_2'
subplot(4,2,4);
subplot(4,2,5);
title 'Conv_1'
subplot(4,2,6);
title 'Conv_1'
subplot(4,2,8);
title 'Conv_2'
Figure:
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:
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);
end
n = n1(1):n2(end);
y = x1 - x2;
end
Main code:
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 )
Figure:
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.
The End