Sei sulla pagina 1di 64

Registration No: Section: Date: ______________

Department of Electrical Engineering

CIIT,Wah

Lab: DSP

LAB# 1
Matlab Review
1.1 Overview
MATLAB will be used extensively in all the labs. The primary goal of this lab is
to familiarize you with basics of MATLAB.

The name MATLAB stands for MATrix LABoratory. MATLAB is a high-


performance language for technical computing. It integrates computation,
visualization, and programming environment. It has sophisticated data
structures, contains built-in editing and debugging tools, and supports
object-oriented programming. These factors make MATLAB an excellent tool
for teaching and research.

1.2 Scalars & Vectors


Matrices are the basic elements of the MATLAB environment. A matrix is a
two-dimensional array consisting of m rows and n columns.

A scalar is a single value, such as 2 or 6.

A vector is a special case of a matrix.An array of dimension 1 x n is called a


row vector, whereas an array of dimension m x1 is called a column vector.
The elements of vectors in MATLAB are enclosed by square brackets and are
separated by spaces or by commas

For example, to enter a row vector, v, type

>> v = [1 4 7 10 13]
Registration No: Section: Date: ______________

Column vectors are created in a similar way; however, semicolon (;) must
separate the components of a column vector.

>> w = [1; 4; 7; 10; 13]

A row vector is converted to a column vector using the transpose operator.


The transpose operation is denoted by an apostrophe or a single quote (').

Note: v (1) is the first element of vector v, v (2) its second element, and so
forth.

Furthermore, to access blocks of elements, we use MATLAB's colon notation


(:). For example, to access the first three elements of v, we write,

>> v(1:3)

Or, all elements from the third through the last elements,

>> v(3: end)

Task (1): What does the following command do?

>> v(:)

1.3 Matrices
To enter a matrix A, such as,

Type A = [1 2 3; 4 5 6; 7 8 9]

The element of row i and column j of the matrix A is denoted by A(i, j).

>> A(3,3) = 0
Registration No: Section: Date: ______________

Often we must deal with matrices or vectors that are too large to enter one
element at a time. For example, suppose we want to enter a vector x
consisting of points (0, 0.1,0.2, 0.3,,5). We can use the command

>> x = 0:0.1:5;
Task(2): Explain what does command linspace do?

Use: help linspace

The colon operator can also be used to pick out a certain row or column. For
example, the

statement A (m:n,k: l) specifies rows m to n and columns k to l.

>> A(2,:)

>> A(:,2:3)

Task (3): What does the following command do?

>> A(:,2)=[ ]

Task (4): What does following command do?

>> A = [1 2 3; 4 5 6; 7 8 9]

>> B = A([2 3],[1 2])

Task 5: What does following command do?

>> size(A)
Registration No: Section: Date: ______________

1.4 Matrix Generators


MATLAB provides functions that generate elementary matrices.

1.5 Matrix & Array arithmetic operations


MATLAB allows arithmetic operations: +, -, *, and ^ to be carried out on
matrices.

On the other hand, array arithmetic operations or array operations for short,
are done element-by-element. The period character . distinguishes the
array operations from the matrix operations.

1.6 Plotting
The MATLAB command to plot a graph is plot(x,y).

where x is a vector representing the abscissa (x-axis) and y is a vector


representing the ordinate (y-axis). More than one function may be plotted on
the same graph. The syntax to graph multiple plots is:
Registration No: Section: Date: ______________

plot(x1,y1,x2,y2,,xn,yn)

It is possible to specify line styles, colors, and markers (e.g., circles, plus
signs, . . . ) using the plot command:

plot(x,y,'style_color_marker')

where style_color_marker is a triplet of values from following table

Specify the components (in any order) as a quoted string after the data
arguments.

Task (6): Type the following commands and observe the plot

t = -5:.01:5;
y = sin (2*pi*t);
plot (t,y);

z = cos (2*pi*t);

plot(t,y,'r',t,z,'k')

Task (7):Explain the following functions

stem, figure, hold, subplot.

You may take help from the following program

>> figure(1)
Registration No: Section: Date: ______________

>> y = [0 1 2 4 2 1 0];

>> subplot(2,2,1);

>> stem(y)

>> subplot(2,2,2);

>> plot(y)

>> figure(2)

>> y = [0 1 2 4 2 1 0];

>> stem(y)

>> hold on

>> plot(y)

>> hold of
Registration No: Section: Date: ______________

DSP Lab#02
Introduction to Matlab (II)

2.1 M-File Scripts


A script file is an external file that contains a sequence of MATLAB
statements. Script files have a filename extension .m and are often called M-
files. M-files can be scripts that simply execute a series of MATLAB
statements.

Use the MATLAB editor to create a file: File New M-File

Another way to open editor is:

>> edit

or >> edit filename.m to open filename.m

Note: Always save the script with .m extension. You can run script by typing
its name in command window e.g >>filename

Task(1): Plot the cosine functions, y1 = 2cos(x), y2 = cos(x), and y3 =


0.5cos(x), in the

interval 0 x 2pi using M-file Script.

Use pi/100 as interval when defining x

% Your code goes here

% Append following statements

xlabel('0 \leq x \leq 2\pi')


ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Cosine plots')
axis([0 2*pi -3 3])
Registration No: Section: Date: ______________

2.2 M-File functions


M-file functions are programs (or routines) that accept input arguments and
return output arguments.

The first line of M-File function starts with the keyword function. It gives the
function

name and order of arguments.

function [outputs] = function_name(inputs)

Note: Name of the text file that you save will consist of the function name
with the extension .m

Example:

function y = amplitude_multiply(x)

y = 3 * x;

Task(2): Explain the following commands!

input, disp, fprintf, fopen, fclose, nargin, nargout

2.3 Control Flow


MATLAB has four control flow structures: the if statement, the for loop, the
while loop,

and the switch statement.


Registration No: Section: Date: ______________

2.3.1 The ifend structure


MATLAB supports the variants of if" construct.

if ... end
if ... else ... end
if ... elseif ... else ... end

The simplest form is

if expression

statements

end

Example:

discr = b*b - 4*a*c;


if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
elseif discr == 0
disp('Discriminant is zero, roots are repeated')
else
disp('Roots are real')
end

2.3.2 Relational and logical operators

2.3.3 The ``for...end'' loop


In the for ... end loop, the execution of a command is repeated at a fixed and
predetermined number of times. The syntax is

for variable = expression


statements
end
Registration No: Section: Date: ______________

e.g for i = 1:5

x= i * i

end

Multiple for loops can be nested

2.3.4 The ``while...end'' loop


This loop is used when the number of passes is not specified. The looping
continues as long as stated condition is satisfied. The while loop has the
form:

while expression
statements
end

e.g x=1
while x <= 10
x = 3*x
end

Note: Other control statements include break, continue, return, switch


etc. Every student should be able to use all these control statements.

2.4 Operator precedence


Registration No: Section: Date: ______________

Task (3): Write a noise function which generates noise signal of length n
with amplitude uniformly distributed in the interval (a, b).

Note: Your function declaration should have three inputs

Lower Limit - a
Upper Limit - b
Length of row vector - n

Hint: rand function generates random numbers uniformly distributed in the


interval (0, 1).

a + (b-a) * 0 = a
a + (b-a) * 1 = b
Registration No: Section: Date: ______________

DSP Lab#03
Discrete Time Signals and Signal Operations

A discrete signal is denoted by x(n), in which the variable n is integer valued


and represents discrete instances in time. For Matlab representation of signal
x(n) we require two vectors, one for sample values and the other for sample
positions.

E.g. x (n) = {2, 1, -1, 0, 1, 4, 3, 7}

>> n=[-3,-2,-1,0,1,2,3,4]; x=[2,1,-1,0,1,4,3,7];

3.1 Unit Sample Sequence

To generate over the interval n1n0n2, we will use the following MATLAB
function

Function [x, n] = impseq (n0, n1, n2)


n = n1:n2; x = [(n-n0) == 0];

Task(1): Write code to generate and plot the following sequence over
interval -5n5

3.1.2 Unit step sequence:

To generate over the interval n1n0n2, we will use the following MATLAB
function

function [x,n] = stepseq(n0,n1,n2)

n = n1:n2; x = [(n-n0) >= 0];


Registration No: Section: Date: ______________

Task(2): Write code to generate and plot the following sequence over
interval 0n20

3.1.3Complex-valued exponential sequence

Task(3): Run the following code and note down the output. Also use real,
imag and abs functions to plot real part, imaginary part and magnitude.

>> n = [0:5]; x = exp ((2+3j)*n);

3.1.4 Sinusoidal Sequence


Task(4): Execute the following code and correctly answer the following
questions

Fs = 100; % Sampling frequency


Freq = 10; % Frequency of the signal
time = 0:1/Fs:(3/Freq); % Time vector
A = 4; % Amplitude of the signal
signal = A * sin(2*pi*Freq*time); % Signal it self
stem(time,signal)
Registration No: Section: Date: ______________

Number of samples in the signal: _____________________


Number of cycles in the plotted signal: ______________
Number of samples in one cycle: ______________________
Time period of signal: _______________________________
Frequency of the signal: _____________________________

Task(5): Explain the following Matlab functions

square, sawtooth, chirp

3.2 Operation on Sequences:

3.2.1 Signal Addition:


If sequences are of unequal lengths, or if the sample positions are diferent
for equal-length sequences, then we cannot directly use the operator +. We
have to first augment x1 (n) and x2 (n) so that they have the same position
vector n.

Following function sigadd is used to accomplish this:

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

n = min(min(n1) ,min(n2)) :max(max(n1) ,max(n2)) ;

y1 = zeros (1,length(n)); y2=y1;

y1 (find((n>=min(n1))&(n<=max(n1))==1))=x1;

y2 (find((n>=min(n2))&(n<=max(n2))==1))=x2;

y = y1+y2;

Note: Signal Multiplication can be carried out in the similar way.


Registration No: Section: Date: ______________

3.2.3 Signal Shifting:


This operation has no efect on x but vector n is changed by adding shifted
amount to each element.

function [y,n] = sigshift(x,m,n0)

n = m+n0; y=x;

3.2.4 Signal Folding


This operation can be carried out by the following function

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

y = fliplr(x); n = - fliplr(n);

Task(6): Let x(n) = {1,2,3,4,5,6,7,6,5,4,3,2,1}. Determine and plot the


following sequence:
Registration No: Section: Date: ______________

DSP Lab#04

Linear Convolution

4.1 Convolution
Convolution is used to calculate the response of a system to arbitrary inputs
by using the impulse response of a system.

Impulse response denoted by h[n] is the signal that exits a system when a
delta function (unit impulse) is the input.

Any arbitrary Input signal can be decomposed into a set of impulses, each of
which can be viewed as a scaled and shifted delta function. Second, the
output resulting from each impulse is a scaled and shifted version of the
impulse response. Third, the overall output signal can be found by adding
these scaled and shifted impulse responses. In other words, if we know a
system's impulse response, then we can calculate what the output will be for
any possible input signal.

Any arbitrary sequence x(n) can be synthesized as a weighted sum of


delayed and scaled unit sample sequences

A discrete time system is described as an operator T[.] that takes a sequence


x(n) (called excitation) and transforms it into another sequence y(n) (called
response).
Registration No: Section: Date: ______________

A discrete system T[.] is a linear operator L [.] if and only if L[.] satisfies the
principle of superposition. So output of liner system becomes

The response is impulse response of system denoted by h(n,k).For


Linear Time invariant systems in which input-output pair is invariant to shift

n in time, h(n,k) becomes h(n-k) and output becomes .

Hence .

4.2 Convolution in Matlab


MATLAB does provide a built-in function called conv that computes the
convolution between two finite duration sequences. The conv function
assumes that the two sequences begin at n=0.

>> y = conv(x, h);

Task(1): Given the following two sequences

Determine the convolution y(n) = x(n)* h(n).

Note: The conv function neither provides nor accepts any timing
information. What is needed is a beginning point and an end point of y(n).
Registration No: Section: Date: ______________

Let then

A simple extension of the conv function, called conv_m, which performs the
convolution of arbitrary support sequences can now be designed

Task(2): Perform convolution of previous exercise using conv_m function.

4.3 Linear Convolution using Matrix-Vector Multiplication


When the sequences x(n) and h(n) are of finite duration Nx and Nh,
respectively, then their linear convolution can be implemented using matrix-
vector multiplication.

If elements of y(n) and x(n) are arranged in column vectors x and y


respectively, then

y=Hx
Registration No: Section: Date: ______________

where linear shifts in h(n-k) for n = 0,. . . , Nh - 1 are arranged as rows in the
matrix H.This matrix has an interesting structure and is called a Toeplitz
matrix.

Consider the sequences

The vector representation will be:

Note that each diagonal of H contains the same number. Note carefully that
the first column of H contains the impulse response vector h(n) followed by
number of zeros equal to the number of x(n) values minus one. The first row
contains the first element of h(n) followed by the same number of zeros as in
the first column.

MATLAB provides a function called toeplitz to generate a Toeplitz matrix,


given the first row and the first column. Using this function and above
properties we can develop an alternate MATLAB function to implement linear
convolution as follow

function [y,H]=conv_tp(h,x)
% Linear Convolution using Toeplitz Matrix
% -------------------------------------------------------------------------------------
% [y,H] = conv_tp(h,x)
% y = output sequence in column vector form
% H = Toeplitz matrix corresponding to sequence h so that y = Hx
% h = Impulse response sequence in column vector form
% x = input sequence in column vector form
Nx = length(x); Nh = length(h);
hc = [h; zeros(Nx-1, 1)];
hr = [h(1),zeros(1,Nx-1)];
H = toeplitz(hc,hr);
y = H*x;
Registration No: Section: Date: ______________

Task(3): Determine the linear convolution of following sequences using


matrix-vector multiplication
Registration No: Section: Date: ______________

DSP LAB#05

Discrete Time Fourier Transform (DTFT)

DTFT transforms an absolutely sumable discrete signal x(n) into a complex-


valued continuous periodic function X(ejw) of real variable w, called a digital
frequency, which is measured in radians.

The inverse discrete time Fourier transform (IDTFT) of X(ejw) is given by

Task 1: Determine the discrete-time Fourier transform of the following finite-


duration sequences:


Registration No: Section: Date: ______________

Note:

DTFT is periodic in w with period 2pi.


For real-valued x(n), X(ejw) is conjugate symmetric.

So to plot X(ejw), we now need to consider only a half period of X(ejw).


Generally, in practice this period is chosen to be [0 pi].

Matlab code for evaluating in Task 1, at 501 equispaced


points between [0, pi] and plotting its magnitude is given below

If we evaluate X(ejw) at equispaced frequencies between [0,pi],then DTFT


expression

can be implemented as a matrix-vector multiplication operation.

To evaluate X(ejw) at (M+1) equispaced frequencies

DTFT expression can be written as

where are arranged as column vectors, x and X, and


W is given by

To represent as row vector, we take transpose of above and get

.
Registration No: Section: Date: ______________

.This expression can be implemented in


Matlab as follow:

>> k = [0:M];
>> X = x * (exp(-j*pi/M)) .^ (n * k);
Task 2: Compute the discrete time Fourier transform of the sequence

at 501 equispaced frequencies between [0, pi].Also plot


magnitude, real part, imaginary part and angle of X(ejw).

For plotting over w axis use w=[0:M]*pi/M;

Task 3: Write a MATLAB function to compute the DTFT of a finite-duration


sequence. The format of the function should be

Function [X, w] = dtft (x,n,M)

% Computes Discrete-time Fourier Transform

% x = finite duration sequence over n

% n = sample position vector

% M = no of equispaced frequencies

% w = Frequency location vector


Registration No: Section: Date: ______________

Task4: Using above DTFT function compute DTFT of the following sequence

x(n) = 2(0.8)n[u(n)-u(n-20)]

Take -30 n 30

Also plot Magnitude, Real part, Imaginary part and Angle of X(ejw).
Registration No: Section: Date: ______________

DSP LAB#06
Properties of DTFT & Frequency Response of LTI Systems

6.1 Properties of DTFT


Let X (ejw) be the discrete time Fourier transform of x(n).

Linearity:

Time Shifting:

Frequency Shifting:

Conjugation:

Folding:

Convolution:

Multiplication:

Task 1: Using properties of DTFT, determine and plot DTFT of the following
sequence

x = T10(n) * T10(-n)
Registration No: Section: Date: ______________

where and

6.2 Frequency Domain Representation of LTI Systems


Frequency Response:

The discrete-time Fourier transform of an impulse response is called the


Frequency Response (or Transfer Function) of an LTI system and is denoted
by

LTI System can be represented in frequency domain by:

Task 2: Determine the frequency response H(ejw) of a system characterized


by h(n) =(0.5)|n| cos(0.1n). Plot the magnitude and the phase responses.
Take n=0:10;
Registration No: Section: Date: ______________

6.3 Difference Equations:


An LTI discrete system can also be described by a linear constant coefficient
diference equation of the form

Matlab Implementation using FILTER routine:

A routine called filter is available to solve diference equations numerically,


given the input and the diference equation coefficients.

Where

And x is input sequence array. Length of y is same as x.

E.g. for system described by

coefficient arrays are

b = [1]; a = [1 -1 0.9];

Note: If roots of a are less than 1 than system is stable.

6.3.1 Frequency response using Matrix Vector Multiplication


Implementation:
When an LTI system is represented by the diference equation then
frequency response can be evaluated as
Registration No: Section: Date: ______________

If we evaluate H(ejw) at k = 0,1,.,K equispaced frequencies over [0,pi] and


let {bm}, {al} (with a0= 1), {m = 0,. . . , M}, {l = 0,. . . , N } , and {wk} be
arrays (or row vectors),then numerator and denominator in above relation
becomes

Now above relation can be computed using ./ operation.

Task 3: Plot magnitude and phase response for filter described by

Hint: Take m = 0: length(b)-1; l = 0:length(a)-1;


Registration No: Section: Date: ______________

DSP Lab#07

z-Transform

The z-transform is a useful tool in the analysis of discrete-time signals and systems
and is the discrete-time counterpart of the Laplace transform for continuous-time
signals and systems. Discrete-time Fourier transform (DTFT) exist for absolutely
summable sequences. Unfortunately, many of the signals that we would like to
consider are not absolutely summable and, therefore, do not have a DTFT.

The z-transform is a generalization of the DTFT that allows one to deal with such
sequences and is defined as

where z is a complex variable. The set of z values for which X(z) exists is called the
region of convergence (ROC) and is given by

for some positive numbers Rx- and RX+

Note:Rx- may be equal to zero and/or RX+ could possibly be inf.

Let X(z) be rational function given as

Then the roots of B(z) are called the zeros of X(z), while the roots of A(z) are called
the poles of X(z).
Registration No: Section: Date: ______________

7.1 Properties of ROC:


The ROC is always bounded by a circle since the convergence condition is on
the magnitude |z|.
For a right-sided sequence that is zero for some n < n o ROC is always outside
of a circle of radius Rx- If no 0, then the right-sided sequence is also called a
causal sequence.
For a left-sided sequence that is zero for some n > n o ROC is always inside of
a circle of radius Rx+
If no 0, the resulting sequence is called an anticausal sequence.
The ROC cannot include a pole.
The ROC is one contiguous region; that is, the ROC does not come in pieces.

7.2 Important Properties of Z-Transform:

Linearity:

Sample shifting:

Frequency shifting:

Folding:

Convolution:

Example (1): Let X1(z) = 2+3z-1 +4z-2 and X2(z)= 3+4z-1+5z-2+6z-3. Determine
X3(z)=X1(z)X2(z).

From the definition of the z-transform we observe that

Then the convolution of the above two sequences will give the coefficients of the
required polynomial product.

So X3(z) will be

Task(1):Let X1(z) = z+2+3z-1 and X2(z) = 2z2+4z+3+5z-1.Determine


X3(z)=X1(z)X2(z).
Registration No: Section: Date: ______________

7.3 Some common Z-Transform Pairs:

7.4 Inversion of z-Transorm


The most practical approach is to use the partial fraction expansion method. It
makes use of the z-transform Table. The z-transform, however, must be a rational
function.

Matlab Implementation:

[R,p,C]=residuez(b,a) finds the residues, poles, and direct terms of X(z) in


which two polynomials B(z) and A(z) are given in two vectors b and a, respectively
and partial fraction is given as
Registration No: Section: Date: ______________

where p(k) is a pole of multiplicity r.

After this z-transform table is used to find inverse z-transfom.

Similarly, [b ,a] =residuez(R,p ,C), with three input arguments and two output
arguments, converts the partial fraction expansion back to polynomials with
coefficients in row vectors b and a.

Example(2)Let

First rearranging X ( z ) so that it is a function in ascending powers of z -1.

So X(z) will be:

Task(2): Compute the inverse z-transform of

Use .Here poly computes polynomial coefficients given


roots.
Registration No: Section: Date: ______________

7.5: System Representation in z-domain:


The system function H(z) is given as

Matlab Function freqz returns the N-point frequency vector w and the N-point
complex frequency response vector H of the system, given its numerator and
denominator coefficients in vectors b and a.

[H,w] = freqz(b,a,N)

The function zplane (b, a) plots poles and zeros, given the numerator row vector
b and the denominator row vector a.

Task(3):Given

(a)Sketch pole-zero plot (b) Plot Magnitude response |H(e jw)| and Phase response
<H(ejw)

(c) Determine the impulse response h(n).

Note:Use b = [1 0] and take N = 100.


Registration No: Section: Date: ______________

DSP Lab#0 8

Discrete Fourier Transform (DFT)

The discrete time Fourier transform (DTFT) provided the frequency-domain (w)
representation for absolutely summable sequences. This transform is defined for
infinite-length sequences and is function of continuous variable (w). These two
features are troublesome because one has to evaluate infinite sums at uncountable
infinite frequencies. This problem is solved by DFT which is defined for discrete
signal whose non-zero values have a limited (finite) duration. It is obtained by
sampling the discrete time Fourier transform in the frequency domain. Such a
representation is very useful for digital computations and for digital hardware
implementation.

8.1 DFT
The Discrete Fourier Transform of an N-point sequence is given by

where the matrix WN is given by


Registration No: Section: Date: ______________

Here WN = e-j*2pi/N
and IDFT is given as

Matlab Implementation:

DFT & IDFT functions can be implemented as:

Task (1): Let x (n) be a 4-point sequence

(a)Compute DTFT and plot its magnitude

(b)Compute 4-point DFT and plot its magnitude.


Registration No: Section: Date: ______________

To get high density spectrum, zero padding operation is used in which zeros are
appended with sequence.

Task (2): For sequence of Task (1):

(a) Compute 8-point DFT by appending 4 zeros with the sequence and plot
magnitude
(b) Compute 16-point DFT by appending 12 zeros and plot magnitude.
Registration No: Section: Date: ______________

Note: The zero-padding gives us a high-density spectrum and provides a better


displayed version for plotting. But it does not give us a high resolution spectrum
because no new information is added to the signal. Only additional zeros are added
in the data. To get a high-resolution spectrum, one has to obtain more data from
the experiment or observations.

8.2 Circular Folding


Imagine that the sequence x (n) is wrapped around a circle in the counterclockwise
direction so that indices n = 0 and n = N overlap. Then x ((-n))N can be viewed as a
clockwise wrapping of x(n) around the circle; hence the name circular folding.

In Matlab, the circular folding can be achieved by

x=x(mod(-n,N)+1)

then

Task (3): Let x (n) = 10(0.8)n 0 n 10

Determine and plot x((-n))11

Note: Imagine that the DFT samples are arranged around a circle so that the
indices k = 0 and k = N overlap; then the samples will be symmetric with respect to
k = 0.
Registration No: Section: Date: ______________

8.3 Circular Shift


Imagine that the sequence x (n) is wrapped around a circle. Now rotate the circle by
k samples and unwrap the sequence from 0 n N 1, we will get circular shifted
sequence. First convert x (n) into its periodic extension and then shift it by m
samples and then convert it into N point sequence as

Its DFT is given as

Circular Shift function can be implemented as

Example: Given an 11-point sequence x(n) = 10 (0.8) n, 0 n 10, determine and


plot

8.4 Circular Convolution


A linear convolution between two N-point sequences will result in a longer
sequence. Once again we have to restrict our interval to 0 n N - 1. Therefore
instead of linear shift, we should consider the circular shift. A convolution operation
that contains a circular shift is called the circular convolution and is given by

DFT property for circular convolution is


Registration No: Section: Date: ______________

In Matlab circular convolution can be implemented as

Task(4): Let x1(n) = {1,2,2} and x2(n) = {l, 2,3,4}

Compute (i) (ii) (iii)


Registration No: Section: Date: ______________

Note: If we make both x1( n ) and x2( n ) N = N1+ N2 - 1 point sequences by padding
an appropriate number of zeros, then the circular convolution is identical to the
linear convolution.

DSP Lab#09
Sampling, quantization and digitization

The purpose of this lab is to familiarize students with the concepts of sampling,
quantization and digitization to bits. Firstly a simple sine wave with high sampling
frequency is generated assuming it to be an analog signal. Secondly this assumed
analog signal is sampled. This sampled signal is then quantized to certain levels.
After quantization bits are assigned to each level.

Lab tasks:
Step 1:
Generate the sine wave with
Frequency = 3Hz
Sampling Frequency = 1000 Hz
Amplitude = 1
Number of cycles = 3
Registration No: Section: Date: ______________

Note: Here the sine signal generated is assumed to be an analog signal.

Step 2:
Sample the assumed analog signal. To do so, write the code in following steps
Generate a vector matrix having zeros; the length of this zero vector should
be same as that of assumed analog signal.
Assign the value one 1 to every 40 th sample in the zero vector. Now it is a
pulse train.
Perform element by element multiplication between the assumed analog
signal and pulse train, to obtain the sampled signal.

Note: If plot of assumed analog signal and stem of sampled signal is in the same
figure the sampled values can be seen quite evidently from the figure, as shown
below.
Sampling of an Analog signal
1.5

Analog signal

Sampled values

0.5
A m p lit ud e

-0.5

-1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Time

Step 3:
Quantize the sampled signals. To do so, write the code in following steps
Remove zeros from the sampled signals. (Hint: Apply ~= , == or see help
find).
Assign levels to the sampled signal as shown in the figure below.
Assign bits to the levels as according to the given table.
Registration No: Section: Date: ______________

Amplitude level Assigned Assigned


(A) value bits
A < -0.5 -2 00
-0.5 < A < 0 -1 01
0 < A < 0.5 1 10
A > 0.5 2 11

The quantization done based on levels defined is explained through the figure
below.
2
Quantized Signal
Sampled Signal
1.5

0.5

-0.5

-1

-1.5

-2

0 5 10 15 20 25 30 35 40
Samples
Registration No: Section: Date: ______________

DSP Lab Manual 10

FIR Filters in Matlab

The goal of filtering is to perform frequency-dependent alteration of a signal. A


simple design specification for a filter might be to remove noise above a certain
cutof frequency. A more complete specification might call for a specific amount of
pass band ripple (Rp, in decibels),stop band attenuation (Rs, in decibels), or
transition width (Wp - Ws, in hertz). A precise specification might ask to achieve the
performance goals with the minimum filter order, call for an arbitrary magnitude
response, or require a FIR filter.

10.1 FIR Filter Design in Matlab


Digital filters with finite-duration impulse response (FIR filters) have both
advantages and disadvantages when compared to infinite-duration impulse
response (IIR) filters.

FIR filters have the following primary advantages:


They can have exactly linear phase.
They are always stable, even when quantized.
The design methods are generally linear.
They can be realized efficiently in hardware.
The filter startup transients have finite duration.

The primary disadvantage of FIR filters is that they often require a much
higher filter order than IIR filters to achieve a given level of performance.
Correspondingly, the delay of these filters is often much greater than for an
equal performance IIR filter.

10.2 Impulse Response Revisited


FIR filters are described by diference equations of the form

where the filtered signal y(n) is just a linear combination of current and
previous values
of the input signal x(n). The coefficients b are the numerator coefficients of
the transfer
function. The denominator of the transfer function will always be a = 1. The
order of the
Registration No: Section: Date: ______________

filter is n = length(b) - 1.

10.3 FIR Methods


The Signal Processing Toolbox supports a variety of methods for the design of
FIR filters.

10.4 Linear Phase Filters


A filter whose impulse response is symmetric or antisymmetriac about its
midpoint is called a (generalized) linear phase filter. For such filters,
The DFT of the impulse response will be either purely real or purely
imaginary.
The magnitude of the DFT is scaled by the filter's magnitude response
(there is no amplitude distortion).
The phase shift of a filtered signal will vary linearly with frequency
(pure time delay with no phase distortion).
The phase delay and group delay will be equal
and constant. For an order n linear phase FIR filter, the phase delay
and group delay is n/2.

The absence of either amplitude distortion or phase distortion preserves the


waveform of signals in the passband.

10.5 FIR Filter Types


The symmetric impulse response of a linear phase filter can have an odd or
an even number of points, and can have an odd or even symmetry about the
midpoint, leading to four filter types:
Registration No: Section: Date: ______________

10.6 Window-Based Design


Windowing is a common design method for FIR filters. In this method,

Recall the i.e H(ejw) is periodic and has a


Fourier series.
The corresponding ideal impulse response h(n) is determined by the
inverse Fourier transform. In general, this response cannot be
implemented in a digitalfilter because it is infinite and noncausal.
h(n) is symmetrically truncated (multiplied by a finite, symmetric
window) and shifted to make it causal, to create a linear phase finite
impulse response.
Registration No: Section: Date: ______________

The truncated Fourier series can be shown to be an approximation to the


ideal filter, which is best" in a mean square sense, compared to other
approximations of the same length. However, the abrupt truncation leads to
overshoot (Gibb's phenomenon) and ripples in the spectrum. The undesirable
efects of truncation can be reduced or eliminated by the use of tapered
windows.

10.6.1 Windowing Functions


The Signal Processing Toolbox supports a variety of windows commonly used
in FIR filter design. Typing

>> help window

provides a list of available window functions.

e.g. hamming, kaiser, gausswin, rectwin etc.

Try:

10.6.2 Windowing and Spectra


When a signal is truncated, high-frequency components are introduced that
are visible in the DFT. By windowing the truncated signal in the time domain,
endpoints are assigned a reduced weight. The efect on the DFT is to reduce
the height of the side lobes, but increase the width of the main lobe.
Registration No: Section: Date: ______________

10.6.3 Window Visualization Tool


To window" a filter, the filter impulse response h(n) of size N is multiplied by
a window
of size N. Ideally, the spectrum of a window should approximate an impulse.
The main lobe should be as narrow as possible and the side lobes should
contain as little energy as possible.

The Window Visualization Tool (WVTool) allows you to investigate the


tradeofs among
diferent windows and filter orders.

wvtool(windowname(n))

opens WVTool with time and frequency domain plots of the n-length window
specified in
windowname, which can be any window in the Signal Processing Toolbox.
Several windows can be given as input arguments for comparative display.

Try:
wvtool(hamming(64),hann(64),gausswin(64),rectwin(64))

Note the diference between the spectrum of the rectangular and other
windows.

10.6.4 Window Design and Analysis Tool


Use Win Tool to interactively design windows with certain specifications
and export them to the Matlab workspace.
Most window types satisfy some optimality criterion. The Hann window
improves high-frequency decay (at the expense of larger peaks in the side
lobes). The Hamming window minimizes side lobe peaks (at the expense of
slower high-frequency decay). The Kaiser window has a parameter that can
be tuned to control side lobe levels.

Try:
Registration No: Section: Date: ______________

wintool

Task 1: Comment on the diference between the Rectangular window and


Hamming window with respect to the mainlobe width and side lobe ripples as
a function of the window size.

10.7 Filter Design with FDATool


The Filter Design Toolbox works with Matlab and the Signal Processing
Toolbox to pro-
vide a complete environment for start-to-finish filter design.

The Filter Visualization Tool (FVTool) can be accessed from within the FDATool
by choosing the Full View Analysis option in the Analysis menu or by clicking
the Full View
Analysis button on the toolbar.

Command:

fdatool

Task 2:Design a Lowpass Hamming window FIR filter of Order 5, Fs=1000hz,


Fc=200hz.Plot magnitude and phase response.
(i) What is numerical value of group delay? (ii) Comment on symmetry and
about what point is it symmetric? (iii) What is the filter length (iv) How many
are the poles and zeros? (v) What are Filter Coefficients.
Registration No: Section: Date: ______________

DSP Lab# 11

IIR Filters in Matlab

IIR filters have infinite duration impulse responses; hence they can be
matched to analog filters, all of which generally have infinitely long impulse
responses. The primary advantage of IIR filters over FIR filters is that they
typically meet a given set of specifications with a much lower filter order
than a corresponding FIR filter. This has the obvious implementation
advantages.
IIR filters have nonlinear phase (they cannot have linear phase; they might
almost have
linear phase).

11.1 IIR Filter Types

Butterworth filter
Provides the best Taylor series approximation to the ideal lowpass filter
response at analog frequencies = 0 and = 1; for any order n.
Response is monotonic overall, decreasing smoothly from = 0 to =
inf.This filter is characterized by the property that its magnitude
response is flat in both passband and stopband.
Registration No: Section: Date: ______________

Chebyshev Type I filter


Minimizes the absolute diference between the ideal and the actual
frequency response over the entire passband by using an equal ripple
in the passband. Stopband response is maximally flat. The transition
from passband to stopband is more rapid than for the Butterworth
filter.

Chebyshev Type II filter


Minimizes the absolute diference between the ideal and the actual
frequency response over the entire stopband by using an equal ripple
in the stopband. Passband response is maximally flat. The stopband
does not approach zero as quickly as the type I filter .The absence of
ripple in the passband, however, is often an important advantage.
Registration No: Section: Date: ______________

Elliptic filter
Equiripple in both the passband and stopband. Generally meets filter
requirements with the lowest order of any supported filter type. Given
a filter order n, passband ripple, and stopband ripple, elliptic filters
minimize transition width.

Note: Elliptic filters provide optimal performance in the magnitude-squared


response but have highly nonlinear phase response in the passband (which
is undesirable in many applications) .Butterworth filters, which have
maximally flat magnitude response and require a higher-order N (more
poles) to achieve the same stopband specification. However, they exhibit a
fairly linear phase response in their passband.The Chebyshev filters have
phase characteristics that lie somewhere in between. Therefore in practical
applications we do consider Butterworth as well as Chebyshev filters, in
addition to elliptic filters. The choice depends on both the filter order (which
influences processing speed and implementation complexity) and the phase
characteristics (which control the distortion).

11.2 Analog Prototyping


The principal design technique for digital IIR filters supported by the Signal
Processing Tool-
box is based on the conversion of classical lowpass analog filters to their
digital equivalents.
The technique involves three steps:

1. Find an analog lowpass filter with cutof frequency of 1 and translate this
prototype filter to the desired band configuration.

2. Transform the filter to the digital domain.


Registration No: Section: Date: ______________

3. Discretize the filter.

Alternatively, the butter, cheby1, cheby2 and ellip functions perform all steps
of the filter design and the buttord, cheb1ord, cheb2ord, and ellipord
functions perform minimum order computations for IIR filters.
The design of these filters starts with the following specifications:
1. The passband frequency Wp of the lowpass or highpass filter. It is a
two element vector [Wp1 Wp2] for the design of a bandpass or
bandstop filter, where Wp2>Wp1.
2. The stopband frequency Ws of the lowpass or highpass filter, where
Ws>Wp for the lowpass filter and Ws<Wp for the highpass filter. Ws is
a two element vector [Ws1 Ws2] for the bandpass or bandstop filter.
We have Ws2>Wp2>Wp1>Ws1 for the bandpass filter and
Wp2>Ws2>Ws1>Wp1 for the bandstop filter. All of these frequencies
are specified within the interval [0 1], where 1 represents the Nyquist
frequency.
3. The maximum attenuation Rp (in decibels) in the passband.
4. The minimum attenuation Rs (in decibels) in the stopband.

The four functions to estimate the order of the Butterworth, Chebyshev I,


Chebyshev II, and elliptic filters are given respectively as

After this following functions are called

2N is the order of the Band Pass and Band Stop filters.


Registration No: Section: Date: ______________

For the design of a high pass filter and a bandstop filter, we have to include a
string high and stop as the last argument in the filter functions, for
example,[b,a] = butter(N,Wn,high) for designing a Butterworth highpass
filter and [b,a]=cheby2(N,Rs,Wn,stop) for designing a Chebyshev II
stopband filter.

Example: Design a Chebyshev I (Equiripple) Bandpass filter with Ws1 =


0.25, Wp1 = 0.3, Wp2 = 0.4 ,Ws2 = 0.45,Rp = 0.5, Rs = 50.
[N,Wn]=cheb1ord([0.30.4],[0.250.45],0.5,50);

Note:IIR Filters can also be designed using fdatool.

Task: Design a Butterworth Bandstop filter with Wp1 = 0.18, Ws1 = 0.2, Ws2
= 0.205, Wp2 = 0.24,Rp = 0.5 and Rs = 50 using fdatool.

11.3 Direct IIR Design


Registration No: Section: Date: ______________

Direct design methods find a filter based on specifications in the discrete


domain. Filters with an arbitrary, perhaps multiband,frequency response are
possible.
The statement

[b a] = yulewalk(n,F,D)

returns vectors b and a containing the n + 1 numerator and denominator


coefficients of
the order n IIR filter whose frequency-magnitude characteristics approximate
those given in vectors F and D. F is a vector of frequency points ranging from
0 to 1, where 1 represents the Nyquist frequency. D is a vector containing the
desired magnitude response at the points in F.

Task: Design a 10th-order bandstop filter fitting the following frequency


response data:
Registration No: Section: Date: ______________

DSP Lab#12

12.1 Fast Fourier Transform (FFT)


The fast Fourier transform (FFT) is an efficient algorithm that is used for converting
a time-domain signal into an equivalent frequency-domain signal, based on the
discrete Fourier transform (DFT).

The DFT of a discrete-time signal x(nT) is

The constants W is referred to as twiddle constant

X(K) can be written as:

This results in a total of (N2 - N) complex additions and N2 complex multiplications.


FFT reduces computational complexity from N2 to N log N.

The FFT algorithm takes advantage of the periodicity and symmetry of the twiddle
constants

For a radix-2 (base 2), the FFT decomposes an N-point DFT into two (N/2)-point or
smaller DFTs. Each (N/2)-point DFT is further decomposed into two (N/4)-point DFTs,
and so on. The last decomposition consists of (N/2) two-point DFTs.

12.1.1 DECIMATION-IN-TIME FFT ALGORITHM WITH RADIX-2


The decimation-in-time FFT algorithm is based on splitting (decimating) x(n) into
smaller sequences and finding X ( k ) from the DFTs of these decimated sequences.
Let the input sequence be decomposed into an even sequence and an odd
sequence, or

x(0), x(2), x(4), . . . , x(2n) and x(1), x(3), x(5), . . . , x(2n + 1)

So we get
Registration No: Section: Date: ______________

Using we get

which represents two (N/2)-point DFTs. Let

So

Using the symmetry property of the twiddle constant we get

For example N=8

This results in decomposition of an eight-point DFT into two four-point DFTs with the
decimation-in-time procedure. This decomposition or decimation process is
repeated so that each four-point DFT is further decomposed into two two-point DFTs.
Since the last decomposition is (N/2) two-point DFTs,this is as far as this process
goes.
Registration No: Section: Date: ______________

Note: The smallest transform is determined by the radix of the FFT. For a radix-2
FFT,N must be a power or base of 2, and the smallest transform or the last
decomposition is the two-point DFT.

12.1.2 DECIMATION-IN-FREQUENCY FFT ALGORITHM WITH


RADIX-2
Another class of FFT algorithms may be derived by decimating the output sequence
X(k) into smaller and smaller subsequences.Its final flowgraph for N=8 comes out to
be

Note: A bit-reversal procedure allows a scrambled sequence to be reordered.


For N = 8, represented by three bits.The first and third bits are swapped. This bit-
Registration No: Section: Date: ______________

reversal procedure can be applied for larger values of N. For example, for N = 64,
represented by six bits, the first and sixth bits, the second and fifth bits, and the
third and fourth bits are swapped.

12.2 INTRODUCTION TO C6713 DSK, CCS, SIMULINK &


IMPLEMENTATION

Digital signal processors such as the TMS320C6x (C6x) family of processors are like
fast special-purpose microprocessors with a specialized type of architecture and
instruction set appropriate for signal processing. Based on a very-long-instruction-
word (VLIW) architecture, the C6x is considered to be TIs most powerful processor.

12.2.1 DSP Board Highlights

Texas Instruments TMS320C6713 DSP operating at 225 MHz

An AIC23 stereo codec


8 MB of synchronous DRAM
512 KB of non-volatile Flash memory
4 user accessible LEDs and DIP switches
Configurable boot options
Standard expansion connectors for daughter card use
JTAG emulation through on-board JTAG emulator with USB host interface or
external emulator
Single voltage power supply (+5V)
Registration No: Section: Date: ______________

The DSP interfaces to analog audio signals through an on-board AIC23 codec and
four 3.5 mm audio jacks (microphone input, line input, line output, and headphone
output). The codec can select the microphone or the line input as the active input.
The analog output is sent to both the line out and headphone out connectors. The
line out has a fixed gain, while the headphone out allows for an adjustable gain
connectors.
Registration No: Section: Date: ______________

12.2.2 Simulink, Real-TimeWorkshop, Embedded Target for TI


C6000 DSP and Link for Code Composer Studio: An Overview

Simulink uses a block based approach to algorithm design and implementation.


Real-Time Workshop converts these Simulink models into ANSI C/C++ code that can
be compiled using CCS. The Embedded Target for TI C6000 DSP provides the APIs
required by Real-Time Workshop to generate code specifically for the C6000
platform. Link for CCS is used to invoke the code building process from within CCS
to build an executable. This code can then be downloaded on the target DSP from
where it runs.

Steps:

Use blocks from Simulink and other blocksets to complete the model
Add the Embedded Target for TI C6000 DSP blocks that let your signal sources
and output devices communicate with your C6713 DSK
Add the C6713 DSK target preferences block from the C6000 Target
Preferences library to your model. Verify and set the block parameters for the
target hardware.
select Simulation Configuration Parameters. For Target Selection,
choose the file ti_c6000.tlc. For Simulation and Code generation, un-
select Block reduction optimization and Implement logic signals.
Choose the TI C6000 target sel.. Set Code generation target type to
C6713DSK. Choose the TI C6000 compiler. Set Symbolic debugging. In
Registration No: Section: Date: ______________

the Select tree, choose the Debug category. Select Verbose build here.
Ensure that Solver is set to Fixed type / discrete.

DSP Lab#13

DSK6713 Audio Delay

In this lab you will build a simple audio system that can run on a Texas Instruments
digital signal processor IC. First, you will create a model of the system in
Matlab/Simulink, then you will use tools to compile the model, download it, and run
it on the DSK7613 board, which contains a TI TMS320C6713 DSP IC.

Create the Simulink Model


1. Log in to the PC and bring up Matlab r2009a.
2. Change the working directory to
M:\matlab\work\
Registration No: Section: Date: ______________

3. Bring up the Simulink library browser by typing simulink at the Matlab prompt.
4. Start a new model by clicking on the blank document icon in the Simulink library
browser.
5. Save the model using the File/Save As pulldown. You can name it audio delay or
another descriptive name. Save it in the M:/matlab/work/ directory on your network
drive.
6. In the Simulink library browser, open the Target Support Package TC6 library
group
and select C6000 Target Preferences
7. From the C6000 Target Preferences library, drag C6713DSK to your empty model.
8. A window will pop up. Click Yes in the pop-up, to initialize the model configuration
parameters to the default values.
9. In the Simulink library browser, Target Support Package TC6 library group, select
the
C6713 DSK Board Support library.
10. From the C6713 DSK Board Support library, drag an ADC block and a DAC block
into the model you're building.
11. Go to the Signal Processing Blockset library group and select Signal Operations.
12. From the Signal Operations library, drag the Delay block into the model.
13. Open the Simulink library group and select Commonly Used Blocks.
14. From the Commonly Used Blocks library, drag the Sum block into the model.
Now you should have ve blocks in your model. You need to connect them and set
some
parameters in some of the blocks. The C6713DSK block (Target Preferences) doesn't
have
any connections, it just denes the settings for the DSP board.
15. Put the ADC, Delay, Sum, and DAC blocks in a line from left to right. This order is
the signal
ow for the model.
16. Double-click on the ADC block.
17. Change the ADC source from Line In to Mic In.
18. Note the sampling rate (8 KHz) and the word length (16-bit), then click OK on
the
ADC Source Block Parameters. You'll see the block in your model now says Mic In.
19. Highlight the ADC block by clicking once on it.
20. Hold the Ctrl key down and click on the Delay block. You should see an arrow
connect
the two blocks.
21. Hold the Ctrl key down and click on the Sum block, then click on the DAC block.
There should be arrows connecting all the blocks.
22. Right-click on the second input to the Sum block, hold the mouse button down,
and
move the mouse to create a line about an inch long. The line is dashed red because
it
isn't connected to anything.
23. Release the mouse button, then click again at the unattached end of the arrow,
hold
the button down, then drag over to the arrow between the ADC and the delay and
release the mouse button. Now there is a path from the ADC to the summing block.
(If you have to delete a line, highlight it by clicking on it, then use the delete key.)
Registration No: Section: Date: ______________

24. Double-click on the delay block. Set the delay to 2048 samples. Leave all other
settings
alone and click OK. You'll see the notation on the block change to z2048.
25. You can double-click on the DAC block to see that the settings for sample rate
and
word length match the ADC block. Don't change the settings.
26. Save the model.

Connect the Hardware


The DSK6713 has to be powered and connected to the PC in order to invoke Code
Composer
Studio.
Connect the USB cable between the PC and the DSK6713.
27. Connect the microphone to the MIC IN jack.
28. Connect the speakers to the LINE OUT jack. Make sure the speakers are
powered,
but set the volume low.
29. Plug in the power supply and connect the power cable to the DSK6713.
30. Keep the microphone away from the speakers, to avoid acoustic feedback once
the
program is running on the DSK7613.

Compile, Link, and Run the Model for the DSP Hardware
In the Simulink window, click on the Simulation pulldown, and select Configuration
Parameters.
(a) On the left side of the Configuration Parameters window, there is a \Select"
browser; use it to go to the Solver section and set the Stop time to \inf" (infinite).
(b) Use the browser to go to the Real-Time Workshop section and select Embed-
ded IDE Link CC. Under Project Options, make sure that the System stack size
(MAUs) is set to 8192.
31. Use the browser pane to go to the Real-Time Workshop section and and the
Generate
code button on the right side of the right-hand pane. Click on it.
32. If a window pops up notifying you of unapplied changes, accept the changes.
33. Look in the main Matlab Command Window. You should see a message like
### Connecting to Code Composer Studio(tm) ...
34. It will be at least two full minutes before anything appears to happen in the
Matlab
command window; be patient. (Note that once CCS is running and authenticated,
future use will be much faster.) Check for the animated CCS icon in the system tray
while you wait. Eventually you should see these messages (among others) in
Matlab:
TLC code generation complete.
Building project...
Download done.
then CCS will start up.
35. Bring the CCS window to the front so you can see messages there.
36. If you get an error, you might have to power-cycle the DSK board and close CCS,
then
Registration No: Section: Date: ______________

click on the Generate code button to re-start the process. You should see a window
pop up briey saying that it is downloading the compiled program to the DSK6713.
37. Once you see \**starting the model**" in the CCS message pane, and a green
light
and the message \RUNNING" in the border at the lower left of the CCS window, you
should be able to try the model. In the command window you should see \Download
done". Snap your fingers or tap the microphone and listen for the output.

Potrebbero piacerti anche