Sie sind auf Seite 1von 121

ELECTRONICS & COMMUNICATION ENGINEERING

MATLAB: An Introduction
1. MATLAB Commands
To do work in MATLAB, you type commands at the >> prompt. Often these
commands will look like standard arithmetic. Or function calls similar to many other
computer languages. By doing this, you can assign sequences to variables and then
manipulate them many ways. You can even write your own functions and programs
using MATLAB's control structures. The following sections will describe the most
commonly used commands on MATLAB and give simple examples using them.

To make life easier, MATLAB includes a simple line-editing facility. If you make an
error while typing a command, you don't have to retype the whole command. You
can just call up the last line you typed and fix the error. To recall the last line you
typed, hit the up arrow. MATLAB actually saves several of your last commands, so
you can continue moving backwards through your prior commands by hitting the up
arrow more than once. If you happen to move too many commands backwards, you
can hit the down arrow to move to the next command (i.e. the one you just went past
by hitting the up arrow). The left and right arrows move you left and right one
character, respectively. Similarly, Ctrl-L and Ctrl-R will move you left and right one
word. Ctrl-B will move you to the beginning of the line, and Ctrl-E will move you to the
end of the line. Ctrl-A will toggle you between insert and overwrite mode for line-
editing. Finally, as you might well expect, backspace will delete the character to the
left of the cursor.

1.1. Basic Terminology


MATLAB has some basic terms and predefined variables you should get familiar with
before going any further. One of these is the variable ans. When you type most
commands to MATLAB, they will return values. You can assign these values to
variables by typing in equations. For example, if you type

>>x=5

MATLAB will print


x=
5

DIGITAL SIGNAL PROCESSING LAB 1


ELECTRONICS & COMMUNICATION ENGINEERING

and assign the number five to the variable x. MATLAB uses ans for any expression
you don't assign to a variable. For instance, if you type
>> 5
to MATLAB, MATLAB will return
ans =
5
and assign the value 5 to the variable ans. Thus, ans will always be assigned to the
most recently calculated value you didn't assign to anything else.
MATLAB creates a variable called eps every time you run it. eps is the distance from
1.0 to the next largest floating point number. Basically, it is the maximum resolution
of the system for floating point arithmetic. On the 486 PC workstations, eps =
2.2204e-016. MATLAB also keeps a permanent variable named pi, which is defined
as 3.1415.... The permanent variable Inf represents the IEEE positive infinity. This
should be returned by evaluating an expression such as 1.0/0.0. Similarly, the
permanent variable NaN represents a value which is not a number, such as the result
of evaluating 0.0/0.0.
As the earlier examples showed, whenever you type a command to MATLAB,
MATLAB returns the value returned, and the variable to which that value was
assigned. Sometimes, you don't want to see this. For example, if you assign b to be
the integers from I to 1000, you probably don't want to wait for MATLAB to print them
all out. If you terminate a command with a semi-colon, MATLAB will suppress the
printing of the variable name and value resulting from the calculation. For example, if
you type
>> x = 5;
MATLAB will assign the value five to the variable x, but rather than tell you it did that,
it will just return another >> prompt.
MATLAB works with two basic types of data objects: scalars and matrices. MATLAB
also has vectors. Vectors are a special case of matrices which are only 1 row by any
number of columns. Vectors can be used to represent discrete-time sequences. We
showed earlier how to assign a scalar, such as five, to a variable. To assign x to be
a matrix by explicitly entering the elements, you type the list of elements separated
by blanks or commas surrounded by [ and ], and use semi-colons to separate the
rows. For example, typing
>>x=[2468; 1 357]

DIGITAL SIGNAL PROCESSING LAB 2


ELECTRONICS & COMMUNICATION ENGINEERING

results in
x= 2 4 6 8
1 3 5 7
The MATLAB workspace is defined as the collection of all the variables you have
defined during the current MATLAB session. A session is defined as beginning when
you type the command matlab to Athena, and ends when you type the quit command
to MATLAB. While MATLAB has room for a substantial amount of variables, it can
get very full if you are working with large vectors or matrices. Shortly, we will show
you how to see what variables are in your workspace, and how to save your
workspace so you can continue your session later.
MATLAB can do complex arithmetic. However, it does not explicitly create a variable
named i. You will need to do this yourself if you want to enter complex numbers. You
can do this by typing
>> i=sqrt(- 1)
MATLAB will return:
i=
O + 1.000I
You can name this variable j if your tastes run that way. Now, you can use complex
numbers of the form a + bi simply by typing a + b*i. For example, to set y = 2 + 3i,
you would type

>> y = 2+3*i
At times, you will want to deal with just a part of a vector or matrix. To do this, you
need to use MATLAB's indexing facility. To get the nth element of the vector x, you
type x(n). MATLAB starts counting from one when numbering vector elements, so the
first element of x is x(l) and not x(O). C hackers should be especially careful about
this. You can also use indices on matrices. The element in the ith row, jth column of
x is x(i,j).

1.2. Basic Arithmetic


MATLAB uses a straightforward notation for basic arithmetic on scalars. The symbol
+ is used to add scalars, so x=1+5 will give x the value 6. Similarly, MATLAB uses -
for subtraction, * for multiplication, / for division, and ^ for exponentiation. All of these
work for two scalars. In addition, you can add, subtract, multiply or divide all the
elements of a vector or matrix by a scalar. For example, if x is a matrix or vector,
then x+1 will add one to each element of x, and x/2 will divide each element of x by 2.

DIGITAL SIGNAL PROCESSING LAB 3


ELECTRONICS & COMMUNICATION ENGINEERING

x^2 will not square each element of x. We'll show you how to do that later. All of the
basic operations (+, -, *, /, and ^) are defined to work with complex scalars.

Another useful operator is the colon. You can use the colon to specify a range of
numbers. Typing
>>x= 1:4will return
x=
1 2 3 4

You can optionally give the colon a step size. For instance,

>>x=8:-1:5 will give

x=
8 7 6 5
and

>> x = 0:0.25: 1.25

will return

x=
0 0.25 0.5 0.75 1.0 1.25

The colon is a subtle and powerful operator, and we'll see more uses of it later.

1.3. Help
MATLAB has a fairly good help facility. The help function knows about all the
commands listed in this manual. Typing help function will tell you the syntax for the
function, i.e. what arguments it expects. It will also give you a short description of
what the command does. If you think you are doing something right, but MATLAB
claims you are in error, try looking at the help for the functions you are using. Later,
when we discuss writing your own functions, we will show you how to include help
info for your functions. This can be very useful for other people using your function,
or for your own use if you haven't used the function for a while.
1.4. Basic Matrix Constructors and Operators
MATLAB has a variety of built-in functions to make it easier for you to construct
vectors or matrices without having to enumerate all the elements.The ones function
will create a matrix whose elements are all ones. Typing ones(m,n) will create an m
row by n column matrix of ones. To create a discrete-time signal named y assigned
to a vector of 16 ones, you would type y = ones(1,16);. Also, giving ones a matrix as
its only argument will cause it to return a matrix of ones the same size as the
argument. This will not affect the original matrix you give as an argument,

DIGITAL SIGNAL PROCESSING LAB 4


ELECTRONICS & COMMUNICATION ENGINEERING

Though, If x = [ I 2 3 4; 0 9 3 8], typing ones(x) will create a matrix of ones that is two
rows by four columns. The zeros function is similar to the ones function. Typing
zeros (m, n) will create an m-by-n matrix of zeros, and zeros(x) will create a two-by-
four matrix of zeros, if x is defined the same way as above.
The maximum and minimum functions are used to find the largest and smallest
values in a vector. If z = [1 2 -9 3 -3 -5], max(z) will return 3. If you call max with a
matrix as an argument, it will return a row vector where each element is the
maximum value of each column of the input matrix. Max is also capable of returning
a second value: the index of the maximum value in the vector. To get this, you
assign the result of the call to max to be a two element vector instead of just a single
variable. If z is defined as above, [a b] = max(z) will assign a to be 3, the maximum
value of the vector, and b to be 4, the index of that value. The MATLAB function min
is exactly parallel to max except that it returns the smallest value, so min(z) will return
-9.
Sum and prod are two more useful functions for matrices. If z is a vector, sum(z) is
the sum of all the elements of z. Similarly, prod(z) is the product of all the elements
of z.

Often, it is useful to define a vector as a subset of a previously defined vector. This is


another use of the colon operator. If we have z defined as in the min/max examples,
z(2:5) will be the vector [2 -9 3 -3]. Again, remember that MATLAB indexes vectors
such that the first element has index one, not zero.
The MATLAB size function will return a two element vector giving the dimensions of
the matrix it was called with. If x is a 4 row by 3 column vector, size(x) will return the
vector [4 3]. You can also define the result to be two separate values as shown in
the max example. If you type [m n] = size(x), m will be assigned to the value 4, and n
to the value 3. The length operator will return the length of a vector. If z is defined
as 14 3 91, length(z) will return 3. Basically, length(z) is equivalent to max(size(z)).
1.5. Element-wise Operations
We will often want to perform an operation on each element of a vector while doing a
computation. For example, we may want to add two vectors by adding all of the
corresponding elements. The addition (+) and subtraction (- operators are defined to
work on matrices as well as scalars. For example, if x = [1 2 3] and y = [5 6 2], then
x+y will return [6 8 5]. Again, both addition and subtraction will work even if the
elements are complex numbers.

DIGITAL SIGNAL PROCESSING LAB 5


ELECTRONICS & COMMUNICATION ENGINEERING

Multiplying two matrices element by element is a little different. The * symbol is


defined as matrix multiplication when used on two matrices. To specify element-wise
multiplication, we use, *. So, using the x and y from above, x.*y will give [5 12 6]. We
can do exponentiation on a series similarly. Typing x.^2 will square each element of
x, giving [ I 4 9]. Finally, we can't use / to divide two matrices element-wise, since /
and \ are reserved for left and right matrix "division." So, we use the./function,

which means that y./x will give [5 3 0.6666]. Again, all of these operations work for
complex numbers.
The abs operator returns the magnitude of its argument. If applied to a vector, it
returns a vector of the magnitudes of the elements. For instance, if x = [2 -4 3-4*i -3
kid, typing
>> y = abs(x)
will return
y=
2 4 5 3
The angle operator will return the phase angle of its operand in radians. The angle
operator will also work element-wise across a vector. Typing
>> phase = angle(x)
will give

phase =
0 3. 14 1 6 -0.9273 - 1.5708
The sqrt function is another commonly used MATLAB function. As you might well
expect, it computes the square root of its argument. If its argument is a matrix or
vector, it computes the square root of each argument. If we define x = [4 -9 i 2-2*I],
then typing

>> y = sqrt(x)
gives
y= 2.00000 3.0000i 0.7071 i 1.5538 -0.6436i
MATLAB also has operators for taking the real part, imaginary part, or complex
conjugate of a complex number. These functions are real, imag and conj,
respectively. They are defined to work element-wise on any matrix or vector.
MATLAB includes several operators to round fractional numbers to integers. The
round function rounds its argument to the nearest integer. The fix function rounds its
argument to the nearest integer towards zero, e.g. rounds "down" for positive

DIGITAL SIGNAL PROCESSING LAB 6


ELECTRONICS & COMMUNICATION ENGINEERING

numbers, and "up" for negative numbers. ceil rounds its argument to the nearest
integer towards positive infinity, e.g. "up", and floor rounds its argument to the
nearest integer towards negative infinity, e.g. "down." All of these commands are
defined to work element-wise on matrices and vectors. If you apply one of them to a
complex number, it will round both the real and imaginary part in the manner
indicated. Typing
>> ceil(3.1 +2.4* i)
will return
ans = 4.0000 + 3.0000i
MATLAB can also calculate the remainder of an integer division operation. If x = y *
n + r, where n is an integer, then rem(x,y) is r.
The standard trigonometric operations are all defined as element-wise operators.
The operators sin, cos and tan calculate the sine, cosine and tangent of their
arguments. The arguments to these functions are angles in radians. Note that the
functions are also defined on complex arguments, which can cause problems if you
are not careful. For instance, cos(x+iy) = cos(x)cosh(y) - i sin(x)sinh(y). The inverse
trig functions (acos, asin and atan) are also defined to operate element-wise across
matrices. Again, these are defined on complex numbers, which can lead to problems
for the incautious user. The arctangent is defined to return angles between pi/2 and -
pi/2.
In addition to the primary interval arctangent discussed above, MATLAB has a full
four quadrant arctangent operator, atan2. atan2(y,x) will return the angle between -pi
and pi whose tangent is the real part of y/x. If x and y are vectors, atan2(y,x) will
divide y by x element-wise, then return a vector where each element is the four-
quadrant arctangent of corresponding element of the y/x vector.
MATLAB also includes functions for exponentials and logarithms. The exp operator
computes e to the power of its argument. This works element-wise, and on complex
numbers. So, to generate the complex exponential with a frequency of pi/4, we could
type
>> n = 0:7;
>> s = exp(i*(pi/4)*n)
s = Columns 1 through 4
1.0000 0.7071 + 0.7071 I 0.0000 + 1.0000i -0.7071 + 0.7071 i
Columns 5 through 8
-1.0000 + 0.0000i -0.7071 i - 0.7071 i 0.0000 - 1.0000i
0.7071 -0.7071 i

DIGITAL SIGNAL PROCESSING LAB 7


ELECTRONICS & COMMUNICATION ENGINEERING

MATLAB also has natural and base-10 logarithms. The log function calculates
natural logs, and log l0 calculates base-10 logs. Again, both operate element-wise
for vectors. Both also come complete with the now-familiar caveat that they are
defined for complex values, and that you should be careful about passing them
complex arguments if you don't know how complex logs are defined.
1.6. Graphics
MATLAB has several commands to allow you to display results of your computations
graphically. The plot command is the simplest way of doing this. If x is a vector,
plot(x) will plot the elements of x against their indices. The adjacent values of x will
be connected by lines. For example, to plot the discrete-time sequence that is a
sinusoid of frequency pi/6, you would type:
>>n=0:11;
>> y = sin((pi/6)*n);
>> plot(y)
Shortly after you enter the plot command, MATLAB will prompt you for a location to
open the graphics window. Just move the mouse to put the window where you want
it, then click the left button. After MATLAB plots the graph, it will wait for you to hit a
key while the mouse is in either the MATLAB text window or graphics window before
it will continue with the MATLAB >> prompt. If you run the commands above, you will
notice that the first value graphed has an abscissa value of one, and not zero. This is
because MATLAB indexes vector elements beginning with one, not zero. Plot will
use the values of y for the y-axis, and their indices for the x-axis. To obtain a graph
of y versus n, you would type
>> plot (n, y)
If plot gets two vectors for arguments, it creates a graph with the first argument as
the abscissa values and the second vector as ordinate values. You can also change
the type of line used to connect the points by including a third argument specifying
line type. The format for this is plot(x, y,'line-type') where line-type is - for a solid line,
- for a dashed line, for a dotted line, and -. For a line of alternating dots and dashes
whichever character you chose to use must be enclosed by single quotes. For
instance, plot (n, y,':') would create the same graph as above, except that the points
would be connected by a dotted line. The default line type is solid. Thinking carefully,
we see that in this case, it is misleading to connect the adjacent values by lines,
since we are graphing a discrete-time sequence. Instead, we should just put a mark
to indicate each sample value. We can do this by using a different set of characters
in place of the line-type argument.

DIGITAL SIGNAL PROCESSING LAB 8


ELECTRONICS & COMMUNICATION ENGINEERING

If we use a period, each sample is marked by a point. Using a + marks each sample
with a + sign, * uses stars, o uses circles, and x uses x's. So, typing
>> plot (n, y,'o')

will plot the values of y against their indices, marking each sample with a circle. We
can also plot several graphs on the same axis. Typing
>> Plot(x 1, y 1, x2, y2)
will graph y I vs. x 1 and y2 vs. x2 on the same axis. You can also include a specific
line or point type for each graph if you want by typing
>> Plot(x me, y 1, ‘line-type 1’, x 2, y2, ‘1ine-type2’
where the line-types can be any of the characters listed above to specify line or point
types.
You can also create plots with either or both axes changed to log-scale. All of these
functions follow the same conventions for arguments and line or point types as plot.
Using log log will create a plot with both axes as log scales. For a plot with only one
axis on log scale, semi logy will create a plot where the x-axis is linear and the y-axis
is logarithmic; while semilogy will have a linear y-axis and logarithmic x-axis.

You can use additional MATLAB commands to title your graphs, or put text labels on
your axes. Typing title ('Beware of the aardvark') will label the current graph at the
top with the text enclosed in single quotes. In this case, that is "Beware of the
aardvark." Likewise, you can label your x- and y-axes by typing label ('This is the x-
axis') and label ('This is the y-axis') respectively .
The axis command is used to control manually the limits and scaling of the current
graph. Typing
>> a = axis
will assign a four-element vector to a. The first element is the minimum x-value; the
second is the maximum x-value for the current graph. The third and fourth elements
are the minimum and maximum y-values, respectively. You can set the values of the
axes by calling the axis function with a four-element vector for an argument. These
elements should be your choices for the x- and y-axis limits, in the same order as
specified above.
So, if you type
>> axis ([-10 10 -5 5])
you will rescale the axis in the graphics window so the x-axis goes from -10 to 10,
and the y-axis from -5 to 5. The axis command can be stubborn sometimes, and
round your limits up to new limits it finds easier to draw.

DIGITAL SIGNAL PROCESSING LAB 9


ELECTRONICS & COMMUNICATION ENGINEERING

There's really nothing you can do about it. The hold command will keep the current
plot and axes even if you plot another graph. The new graph will just be put on the
current axes as much as it fits. Typing hold a second time will toggle the hold off
again, so the screen will clear and rescale for the next graph.

You can use the subplot command to split the screen into multiple windows, and then
select one of the sub-windows as active for the next graph. The format of the
command is subplot (xyn) where x is the number of vertical divisions, y is the number
of horizontal divisions, and n is the window to select for the first plot. Both x and y
must be less than or equal to two, and n must be less than or equal to x times y. For
example, subplot (121) will create two full-heights, half-width windows for graphs,
and select the first, e.g. left, window as active for the first graph. After that, unless
you specifically indicate which window is active, MATLAB will cycle through them
with each successive plot. Typing subplot with no arguments will return the graphics
window to its original, single-window state.
You can use the print command to get a hard copy of the current graphics window.
Typing print ('printer-name') will send the current graph to the printer whose name
appears in single-quotes as the argument.
This may take a minute or two to start printing. MATLAB will just sit idle while
generating the graphics file to dump to the printer. If no printer is specified, MATLAB
will send the printout to the default printer for your workstation. Note that MATLAB
can only send printouts to PostScript printers. Also, the implementation of print with
the printer name as an argument is Athena specific, and may not be found in another
implementation of MATLAB.

1.7. Logical Operations


MATLAB allows you to perform boolean operations on vectors element-wise. For the
purpose of boolean algebra, MATLAB regards anything with a non-zero real part as
true, and everything else as false. MATLAB uses & for the boolean and operator, 1
for or, and for not. So, typing

>> [1 0 2 4] & [O 0 1 i]

gives
[

ans =
0 0 1 0
while typing
>> [1 0 2 4] 1 [0 0 1 i]

DIGITAL SIGNAL PROCESSING LAB 10


ELECTRONICS & COMMUNICATION ENGINEERING

will return
ans =
1 0 1 1

In addition, you can run a cumulative boolean or boolean and across all the elements
of a matrix or vector. If v is a vector or matrix, any (v) will return true if the real part of
any element of v is non-zero. Similarly, all (v) will return true if all the elements of v
have non-zero real parts.
You can also compare two vectors element-wise with any of six basic relational
operators, e.g. less-than (<), greater-than (>), equal-to (==), not-equal-to (~=), less-
than or-equal-to (<=), and greater-than-or-equal-to (>=). Typing
>> [1 2345] <= [543 2 11
returns
ans =
1 1 1 0 0
We will see more uses of the relational operators when we discuss MATLAB
programming control structures.

1.8 Interface Controls


When you first start running MATLAB, it is case-sensitive. This means that MATLAB
distinguishes between upper and lower case variable and function names. So, you
can safely have two separate variables named aardvark, and AARDVARK. If you
type casesen, MATLAB will toggle to being non-case-sensitive. Typing it again will
toggle back to the original mode, e.g. case-sensitive.
MATLAB allows you to clear either the command (text) window, or the graphics
window. The clc command will clear the command window, and give you a fresh >>
prompt. The clg command will clear the graphics window and leave it blank.
You can see all the variables defined in your workspace by using the who command.
The whos command will give you the names of all the variables just like who does.
In addition, it will tell you the size of each variable, if that variable is complex, and the
total bytes of space used by all your variables. If you run the who command, and see
that you have variables you are no longer using, you can use the clear command to
remove obsolete variables. For example, typing clear godzilla would delete the
variable named godzilla.

DIGITAL SIGNAL PROCESSING LAB 11


ELECTRONICS & COMMUNICATION ENGINEERING

MATLAB also defines some basic file manipulation utilities, so you can do these
things without quitting and restarting MATLAB. The dir command is identical to the
UNIX ls command. The chair is the same as cd for UNIX, type is UNIX’s cat, and
delete is rm. You can also pass any other UNIX command through by preceding it by
a! So, typing! date will give you the current date and time. All pathnames and
wildcards should work the same as they do in UNIX.

MATLAB's diary command allows you to make a transcript file recording your
session. Typing diary filename will record all the commands you type in filename,
and will also record "most of the resulting output," according to the MATLAB manual.
Graphs will not be recorded, but almost all printed results will be. Typing diary off will
turn the transcript off, and diary on will turn it back on. The file created is in ASCII
format, suitable for editing with Emacs and including in other reports. In fact, this
function was used to generate almost all the examples in this manual.
MATLAB includes commands that allow you to save all or some of your workspace
so you can continue your session later. Typing save filename will save all of your
workspace in a compressed format in a file named filename. mat. If you want to
reload that workspace later to continue, you just type load filename. If you only want
to save some of the variables, you can give the save command the names of the
variables to save.

If you type
>> save aardvark moose wildebeest
MATLAB will save the variables moose and wildebeest in the file aardvark.mat.
1.9. Signal Processing Functions
MATLAB comes with several useful signal processing functions already defined. For
example, if a and b are vectors (a.k.a. discrete-time sequences), then conv (a, b) will
convolve the two vectors. Typing aft (a) will return the Discrete Fourier Transform of
a, and idft (a) is the inverse DFT a. fft (a) will return the Fast Fourier Transform of a,
and ifft (a) is the Inverse FFT. If a is not a radix-two in length, fft and ifft will zero-pad
it so that the number of samples in the sequence is a power of two.

DIGITAL SIGNAL PROCESSING LAB 12


ELECTRONICS & COMMUNICATION ENGINEERING

If we define a and b to represent a system described by the difference equation:


y(n) =: )( i ) *x(n) + b(2) Din- 1 ) + ...+ b(nb)*x(n-nb+l)
- a(2)*y(n-1) -…-a(na)*y(n-na+1)
typing
>>filter (b, a, x)

will return the sequence that is the result of filtering x with that the system defined by
that difference equation. The b and a coefficient vectors should be ordered by
ascending value of delay. If a (I) is not I, filter will normalize a so that it is by dividing
all of a by a (1).

If we define a and b for a system as above, we can also use the freqz command to
evaluate the Z-transform of the system. There are several ways to input values
depending on how you want to evaluate the transform. Typing
>> freqz (b, a, n)
evaluate the z-transform at n evenly-spaced points around the upper half of the unit
circle.
If you type
>> freqz (b, a, n 'whole')
MATLAB will evaluate the transform at n evenly-spaced points around the whole unit
circle. If you assign the result of freqz to a single variable, you will get back the
values at the frequencies, which may be complex. If you assign the result to a two-
element vector, the first element will be assigned to the complex values of the
samples, while the second element will be assigned to a vector of the frequencies the
z-transform was evaluated at. For example, to look at the very simple system y[n] =
x [n - 1], you would type:

>>a= [1];
>>b= [0 1];
>> [h w] = freqz (b, a, 16);
After doing this, h would be defined as the complex-valued samples of the z-
transform, and w would be
the frequencies at which the z-transform was evaluated to get those values. If you
choose n to be a power of two, freqz will run much faster, since it will use the fft
operator. If you don't want evenly-spaced samples around the unit-circle, you can
explicitly specify at which frequencies the z-transform should be evaluated.

DIGITAL SIGNAL PROCESSING LAB 13


ELECTRONICS & COMMUNICATION ENGINEERING

To do this, type freqz (b, a, w) where w is a vector of the frequencies (in radians) at
which to evaluate the z-transform.

1.10. Polynomial Operations


Vectors can also be used to represent polynomials. If you want to represent an Nth-
order polynomial, you use a length N+1 vector where the elements are the
coefficients of the polynomial arranged in descending order of exponent. So, to
define y = x2 - 5x + 6, you would type:
>> y = [1 -5 6];
The MATLAB roots function will calculate the roots of a polynomial for you. If we use
the y from above,
>> roots(y)
will return
ans =
3 2
MATLAB also has the poly function, which takes a vector and returns the polynomial
whose roots are the elements of that vector.
You can use MATLAB to multiply two polynomials using the cony function described
above. The convolution of the coefficient vectors is equivalent to multiplying the
polynomials. The polyval function can tell you the value of a polynomial at a specific
point. For example, polyval(y, 1) would return 2. polyval also works element-wise
across a vector of points, returning the vector where each element is the value of the
polynomial at the corresponding element of the input vector.

1.11. Control Structures


MATLAB includes several control structures to allow you to write programs. The for
command allows you to make a command or series of commands be executed
several times. It is functionally very similar to the for function in C. For example,
typing
for i= 1:4
end
will cause MATLAB to make the variable i count from 1 to 4, and print its value for
each step. So, you would see
I=1
I=2
I=3
I=4

DIGITAL SIGNAL PROCESSING LAB 14


ELECTRONICS & COMMUNICATION ENGINEERING

Every command must have a matching end statement to indicate which commands
should be executed several times. You can have nested for loops. For example,
typing
Form = 1:3
for n= 1:3
x(m,n)=m+n*i;
end
end
will define x to be the matrix

x=
1.0000 + 1.0000i 1.0000 + 2.0000i 1.0000 + 3.0000i
2.0000 + 1.0000i 2.0000 + 9.0000i 2.0000 + 3.0000i
3.0000 + 1.0000i 3.0000 + 2.0000i 3.0000 + 3.0000i
The indentations in the for structure are optional, but they make it easier to figure out
what the commands are doing.
The if command lets you have programs that make decisions about what commands
to execute. The basic command looks like
if a > 0
x=a^2;
end
This command will assign x to be the value of a squared, if a is positive. Again, note
that it has to have an end to indicate which commands are actually part of the if. In
addition, you can define an else clause which is executed if the condition you gave
the if is not true. We could expand our example above to be
if a>0
x = a^2;
else
x = -a^2
end
For this version, if we had already set a to be 2, then x would get the value 4, but if a
was -3, x would be -9. Note that we only need one end, which comes after all the
clauses of the if. Finally, we can expand the if to include several possible conditions.
If the first condition isn't satisfied, it looks for the next, and so on, until it either finds
an else, or finds the end. We could change our example to get

DIGITAL SIGNAL PROCESSING LAB 15


ELECTRONICS & COMMUNICATION ENGINEERING

if a>0
x = a^2;
else if a == 0
x = i;
else
x = -a^2
end
For this command, it will see if a is positive, then if a is not positive, it will check if a is
zero, finally it will do the else clause. So, if a positive, x will be a squared, if a is 0, x
will be i, and if a is negative,
then x will be the negative of a squared. Again, note we only have a single end after
all the clauses.
The third major control structure is the while command. The while command allows
you to execute a group of commands until some condition is no longer true. These
commands appear between the while and its matching end statement. For instance,
if we want to keep squaring x until it is greater than a million,
we would type
while x < 1000000
x = x^2;
end
If we start with x = 2, this will run until x is 4.295 x 109. Everything between the while
line and the end will be executed until the boolean condition on the while line is no
longer true. You have to make sure this condition will eventually stop being true, or
the command will never finish. If it is not initially true, the commands will never be
executed.The pause command will cause MATLAB to wait for a key to be pressed
before continuing. This is useful when you are writing your own functions.
Sometimes you will want to terminate a for or while loop early. You can use the
break command to jump out of a for or while command. For example, you could
rewrite our while example from above to be:
while 1
if x > 1000000
break;
end
x = x^2
end
which will have exactly the same effect.

DIGITAL SIGNAL PROCESSING LAB 16


ELECTRONICS & COMMUNICATION ENGINEERING

1.12. Functions
Finally, we come to the apex of our discussion: writing your own functions for
MATLAB. You do this using M-files. An M-file is an ASCII text file that has a
filename ending with .m, such as aardvark.m. You can create and edit them from
Emacs. There are two classes of M-files, functions and scripts. Functions are more
interesting, so we'll talk about them first. An M-file is a function if the first word in it is
function. A function can just take several arguments or none at all, and return any
number of values.

We will look at several examples grouped by the number of values they return. The
first line of the file specifies the name of the function, along with the number and
names of input arguments and output values.
3.12.1 Functions Returning No Values
A common example of a function that doesn't return any values is one that draws
graphs. It just draws the graphs, then finishes. Here is an example of such a function
function stars (t)
%STARS(T) draws stars with parameter t
n=t*50;
plot (rand (1, n), rand (1, n),',')
% that line plots n random points
title ('My God, Its Full of Stars!’);
% label the graph
This will draw a random sprinkling of dots across the screen. The first line defines
this as a function names stars that takes one argument named t, and doesn't return
anything. The next line is the help comment. Any comments coming immediately
after the first line will re returned by help stars, which would be
%STARS (T) draws stars with parameter t
for this function. A line of comments is indicated by the % character. You can have as
many of these as you want, and the help command will print all of them. Next, the
function defines an internal variable named n to be Fifty times t. This n is totally
unrelated to any variable already defined in the main MATLAB workspace. Assigning
this value will not alter any n you had already defined fore calling the stars function.
You can also see how we put a comment in the middle of the function indication
which command actually drew the stars.
Sometimes, you will need to write several versions of a function before it works
properly. When you use an M-file function for the first time during a session,

DIGITAL SIGNAL PROCESSING LAB 17


ELECTRONICS & COMMUNICATION ENGINEERING

MATLAB reads it in, compiles it, and then remembers that version, If you change the
M-file after using the function, MATLAB won't see it. It will just use the first version it
compiled. To remove the first version, and force MATLAB to read the new one in, you
should use the clear command. If you type clear orangutan, MATLAB will erase the
function orangutan from MATLAB's previously know functions, so the next time you
call orangutan it will read in your new version of orangutan. Make sure you do this
when you fix a bug in a function, or you will be very confused about why MATLAB is
ignoring your changes.

1.12.2 Functions Returning One Value


Next, we look at an example of a function that returns one value.
function y = fact (n)
%Y = FACT (N) computes the factorial of n;
y= 1;
for i = 2:n\
y=y*i;
end
This function will calculate the factorial of its argument. The first line indicates that
this is a function of one argument n, and should return the value of the variable y for
its answer. The for loop will repeatedly multiply y by every value between 2 and n.
Whatever value is finally in y will be returned as the result of the function. For this
function, it is a scalar, but functions can also return vectors or matrices. Again, note
that the variables y, i, and n have absolutely no effect on any variables of the same
name in the main MATLAB workspace.
1.12.3 Functions Returning More Than One Value
If you want to return more than one argument, you can do it by having the function
return a vector of values. The following function is an example of a function that
does this. For instance, the following function returns two vectors. The first vector is
the prime factors less than 10 of the argument. The second indicates how many
times each of these factors is used.
function [factors, times] = primefact (n)
% [FACTORS TIMES] = PRIMEFACT (N)
find prime factors of n
primes = [2 3 5 7]
for i= 1:4

DIGITAL SIGNAL PROCESSING LAB 18


ELECTRONICS & COMMUNICATION ENGINEERING

temp = n;
if (rem (temp, primes (i)) ==0)
factors = [factors primes (i)];
times = [times 0];
while (rem (temp, primes (i)) ==0)
temp = tamp/primes (i);
times (length (times)) = times (length
(times)) +1;
end

end
end

If we call this function with just one argument, i.e. a = prime fact( 10) we will get back
the vector of prime factors, but not the vector indicating how many times each factor
appears in the number. To get both vectors, we should call the function in this
manner:

>> [a b] = prime fact (180)

a=
2 3 5
b=
2 2 1
This way, we get both vectors returned: the primes in a and the number of times
each prime was used in b. From these results, we see that 180=2x2x3x3x5.
1.12.4 Script M-files
As we mentioned earlier, there is a second kind of M-file. The script type M-file is
just a list of commands to execute in sequence. This differs from a function M-file in
that no arguments are needed. Also, the variables inside a script file are the same
ones as in the main MATLAB workspace. If I have a variable named n = 1000, then
execute a script that includes the line n = 2, my variable will now be 2, and not 1000.
To create a script file, just create a file with Emacs that contains the commands you
want executed. A script file should not have the word function in the first line, and
doesn't need the comments for the help command. The filename should still end in
.m though.

DIGITAL SIGNAL PROCESSING LAB 19


ELECTRONICS & COMMUNICATION ENGINEERING

1.13. Advanced Features


The features listed in the following sections are not essential for using MATLAB on
Athena, but are included for the more curious users who want to push MATLAB as
much as possible.

1.13.1 Selective Indexing


Sometimes, you only want to perform an operation on certain elements of a vector,
such as all the elements of the vector that are less than 0.

One way to do this is a for loop that checks to see if each element is less than zero,
and if so, does the appropriate function. However, MATLAB includes another way to
do this. If you say
>>x(x<0) = -x(x<0)
MATLAB will change all the negative elements of the vector x to be positive. The
following sequence of commands illustrates this:
>>x = [-3 -2 0 2 4]
x=
-3 -2 0 2 4
>>x(x<0) = -x(x<0)
x=
3 2 0 2 4
Though this notation can be more confusing than a for loop, MATLAB is written such
that this operation executes much, much faster than the equivalent for loop.
You can also perform operations on a vector conditionally based upon the value of
the corresponding element of another vector. For instance, if you want to divide two
vectors element-wise, you have to worry about what happens if the denominator
vector includes zeros. One way to deal with this is shown below.
>>x= [32024]
x=
3 2 0 2 4
>>y= [1 1 1 1 1]
y=
1 1 1 1 1
>>q = zeros (1, length(y))

DIGITAL SIGNAL PROCESSING LAB 20


ELECTRONICS & COMMUNICATION ENGINEERING

q=
0 0 0 0 0
>>q(x~=0) = y(x~=0). / X(x~=0)
q=
0.3333 0.5000 0 0.5000 0.2500

You can perform this type of conditional indexing with any boolean operator
discussed earlier, or even with boolean operators on the results of functions on
elements of vectors.

For example
>>q ((x<=3) & (q<=0.4)) = q ((x<=3) & (q<=0.4)) + 14
q=
14.3333 0.5000 0 0.5000 0.2500

1.13.2 Functions with Variable Number of Arguments


Anytime you call a function, MATLAB defines a variable inside that function called
margin. margin is the number of arguments with which the function was called. This
allows you to write functions that behave differently when called with different
numbers of arguments. If you specify the function rhino such that the first line of its
M-file file reads:
function hippo = rhino (a, b, c, d)
MATLAB will not get upset if you call rhino with only two arguments. It will just
assume the last two arguments were optional, and not used. MATLAB will set nargin
= 2, and execute the function. If the function tries to do something using the variables
c or d, MATLAB will generate an error message. MATLAB assumes that you will use
nargin to avoid referring to any optional arguments that weren't supplied.

DIGITAL SIGNAL PROCESSING LAB 21


ELECTRONICS & COMMUNICATION ENGINEERING

MATLAB BASICS

A= [16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1];

SUM (A)
MATLAB replies with
Ans=
34 34 34 34

A’ produces
Ans=
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1

And
Sum (A’)’ produces a column vector containing the row sums
Ans=
34
34
34
34

The sum of the elements on the main diagonal is easily obtained with the help of the
diag function, which picks off that diagonal.
diag (A) produces
ans=
16
10
7
1
and

DIGITAL SIGNAL PROCESSING LAB 22


ELECTRONICS & COMMUNICATION ENGINEERING

sum (diag (A)) produces ans = 34


A (1, 4) + A (2, 4) + A (3, 4) + A (4, 4)
This produces ans=34
X = A;
X (4, 5) = 17
X=
[16 3 2 13 0
5 10 11 8 0
9 6 7 12 0
4 15 14 1 17]
The colon operator
The colon is one of MATLab’s most important operators. It occurs in several different
forms. The expression
1:10
is a row vector containing the integers from 1 to 10
1 2 3 4 5 6 7 8 9 10
To obtain nonunit spacing, specify an increment. For example
100:-7:50
is
100 93 86 79 72 65 58 51
And 0: pi/4: pi is 0 0.7854 1.5708 2.3562 3.1416
Subscript expressions involving colons refer to portions of a matrix.
A (1: k, j) is the first k elements of the jth column of A. So sum (A (1:4, 4))
The Magic Function
B = magic (4)
B=
[16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1]
Operators
Expressions use familiar arithmetic operators and precedence rules.
+ Addition
- Subtraction
* Multiplication
/ Division

DIGITAL SIGNAL PROCESSING LAB 23


ELECTRONICS & COMMUNICATION ENGINEERING

\ Left division
(Described in the section on matrices and linear algebra in using MATLAB)
^ Power
‘Complex conjugate transpose
( ) Specify evaluation order
Generating Matrices
MATLAB provides four functions that generate basic matrices:
Some examples:
Z = zeros (2, 4)
Z=
0000
0000
F = 5*ones (3, 3)
F=
555
555
555
N = fix (10*rand (1, 10))
N=
4944852680
Zeros all zeros
Ones All ones
rand Uniformly distributed random elements
randn Normally distributed random elements
15
R=
1.0668 0.2944-0.6918-1.4410
0.0593-1.3362 0.8580 0.5711
-0.0956 0.7143 1.2540-0.3999
-0.8323 1.6236-1.5937 0.6900

DIGITAL SIGNAL PROCESSING LAB 24


ELECTRONICS & COMMUNICATION ENGINEERING

1. TO STUDY THE ARCHITECTURE OF DSP CHIPS –


TMS 320C SX/6X INSTRUCTIONS.

The C6711™ DSK builds on TI's industry-leading line of low cost, easy-to-use DSP
Starter Kit (DSK) development boards. The high-performance board features the
TMS320C6711 floating-point DSP. Capable of performing 900 million floating-point
operations per second (MFLOPS), the C6711 DSP makes the C6711 DSK the most
powerful DSK development board on the market.
The DSK is a parallel port interfaced platform that allows TI, its customers, and third-
parties, to efficiently develop and test applications for the C6711. The DSK consists
of a C6711-based printed circuit board that will serve as a hardware reference design
for TI’s customers’ products. With extensive host PC and target DSP software
support, including bundled TI tools, the DSK provides ease-of-use and capabilities
that are attractive to DSP engineers.

TMS320C6711 DSK Block Diagram

The basic function block diagram and interfaces of the C6711 DSK are displayed
below.
Many of the parts of the block diagram are linked to specific topics.

DIGITAL SIGNAL PROCESSING LAB 25


ELECTRONICS & COMMUNICATION ENGINEERING

The C6711 DSK board is displayed below.


Many of the parts of the board illustration are linked to specific topics. Move the
mouse over the illustration to determine which parts are linked. Click on the portion of
the illustration for which you want to see information.

The C6711DSK has the following features:


• 150-MHz C6711DSP capable of executing 900 million floating-point
operations per second (MFLOPS)

• Dual clock support; CPU at 150MHz and external memory interface (EMIF) at
100MHz

• Parallel port controller (PPC) interface to standard parallel port on a host PC


(EEP or bi-directional SPP support)

• 16M Bytes of 100 MHz synchronous dynamic random access memory


(SDRAM)

• 128K Bytes of flash programmable and erasable read only memory (ROM)

• 8-bit memory-mapped I/O port


• Embedded JTAG emulation via the parallel port and external XDS510 support

DIGITAL SIGNAL PROCESSING LAB 26


ELECTRONICS & COMMUNICATION ENGINEERING

• Host port interface (HPI) access to all DSP memory via the parallel port

• 16-bit audio codec


• Onboard switching voltage regulators for 1.8 volts direct current (VDC) and
3.3 VDC
The C6711 DSK has approximate dimensions of 5.02 inches wide, 8.08 inches long
and 0.7 inches high. The C6711 DSK is intended for desktop operation while
connected to the parallel port of your PC or using an XDS510 emulator. The DSK
requires that the external power supply be connected in either mode of operation (an
external power supply and a parallel cable are provided in the kit).
The C6711 DSK has a TMS320C6711 DSP onboard that allows full-speed
verification of code with Code Composer Studio. The C6711 DSK provides:
• a parallel peripheral interface
• SDRAM and ROM
• a 16-bit analog interface circuit (AIC)
• an I/O port
• embedded JTAG emulation support
Connectors on the C6711 DSK provide DSP external memory interface (EMIF) and
peripheral signals that enable its functionality to be expanded with custom or third
party daughter boards.
The DSK provides a C6711 hardware reference design that can assist you in the
development of your own C6711-based products. In addition to providing a reference
for interfacing the DSP to various types of memories and peripherals, the design also
addresses power, clock, JTAG, and parallel peripheral interfaces.

DIGITAL SIGNAL PROCESSING LAB 27


ELECTRONICS & COMMUNICATION ENGINEERING

Top Side of the Board:

Bottom Side of the Board:

DIGITAL SIGNAL PROCESSING LAB 28


ELECTRONICS & COMMUNICATION ENGINEERING

TMS320C6711 DSP Features:


• VelociTI advanced very long instruction word (VLIW) architecture

• Load-store architecture

• Instruction packaging for reduced code size

• 100% conditional instructions for faster execution

• Intuitive, reduced instruction set computing with RISC-like instruction set

• CPU

• Eight highly independent functional units (including six ALUs and two
multipliers)

• 32 32-bit general-purpose registers

• 900 million floating-point operations per second (MIPS)

• 6.7-ns cycle time

• Up to eight 32-bit instructions per cycle

• Byte-addressable (8-, 16-, 32-bit data)

• 32-bit address range

• 8-bit overflow protection

• Little- and big-endian support

• Saturation

• Normalization

• Bit-field instructions (extract, set, clear)

• Bit-counting

• Memory/peripherals

DIGITAL SIGNAL PROCESSING LAB 29


ELECTRONICS & COMMUNICATION ENGINEERING

L1/L2 memory architecture:

32K-bit (4-K byte) L1P program cache (direct mapped)

32K-bit (4K-byte) L1D data cache (2-way set-associative)

512K-bit (64K byte) L2 unified map RAM/cache (flexible data/program allocation)

32-bit external memory interface (EMIF):

Glue less interface to synchronous memories: SDRAM and SBSRAM

Glue less interface to asynchronous memories: SDRAM and EPROM

Enhanced direct-memory-access (EDMA) controller

16-bit host-port interface (HPI) (access to entire memory map)

Two multi-channel buffered serial ports (McBSPs)

Two 32-bit general-purpose timers

Flexible phase-locked-loop (PLL) clock generator

Miscellaneous

IEEE-1149.1 (JTAG) boundary-scan-compatible for emulation and test support

256-lead ball grid array (BGA) package (GFN suffix)

0.18-mm/5-level metal process with CMOS technology

3.3-V I/Os, 1/8-V internal

C67x (Specific) Floating-Point Instructions:

Alphabetical Listing of 'C67x (Specific) Floating-Point Instructions

A-F G-L M-R S–Z

ABSDP INTDP MPYDP SPDP

ABSSP INTDPU MPYI SPINT

ADDAD INTSP MPYID SPTRUNC

ADDDP INTSPU MPYSP SUBDP

ADDSP LDDW RCPDP SUBSP

CMPEQDP RCPSP

DIGITAL SIGNAL PROCESSING LAB 30


ELECTRONICS & COMMUNICATION ENGINEERING

CMPEQSP RSQRDP

CMPGTDP RSQRSP

CMPGTSP

CMPLTDP

CMPLTSP

DPINT

DPSP

DPTRUNC

DIGITAL SIGNAL PROCESSING LAB 31


ELECTRONICS & COMMUNICATION ENGINEERING

2. TO VERIFY LINEAR CONVOLUTION


Aim: To compute the linear convolution of two discrete sequences.

Theory: Consider two finite duration sequences x (n) and h (n), the duration of x
(n) is n1 samples in the interval 0 ≤ n ≤ (n1 − 1) . The duration of h (n) is n2 samples;
that is h (n) is non – zero only in the interval 0 ≤ n ≤ ( n2 − 1) . The linear or a periodic
convolution of x (n) and h (n) yields the sequence y (n) defined as,

n
Y (n) = ∑ h ( m) x ( n − m)
m =0

Clearly, y (n) is a finite duration sequence of duration (n1+n2 -1) samples.


The convolution sum of two sequences can be found by using following steps

Step1: Choose an initial value of n, the starting time for evaluating the output
sequence y (n). If x (n) starts at n=n1 and h (n) starts at n= n2 then n = n1+ n2-1 is a
good choice.

Step2: Express both sequences in terms of the index m.

Step3: Fold h (m) about m=0 to obtain h (-m) and shift by n to the right if n is positive
and left if n is negative to obtain h (n-m).

Step4: Multiply two sequences x (n-m) and h (m) element by element and sum the
products to get y (n).

Step5: Increment the index n, shift the sequence x (n-m) to right by one sample and
repeat step4.

Step6: Repeat step5 until the sum of products is zero for all remaining values of n.

Program:
%Linear convolution of two sequences
a=input('enter the input sequence1=');
b=input('enter the input sequence2=');
n1=length (a)
n2=length (b)
x=0:1:n1-1;
Subplot (2, 2, 1), stem(x, a);
title ('INPUT SEQUENCE1');
xlabel ('---->n');
ylabel ('---->a (n)');
y=0:1:n2-1;

DIGITAL SIGNAL PROCESSING LAB 32


ELECTRONICS & COMMUNICATION ENGINEERING

subplot (2, 2, 2), stem(y, b);


title ('INPUT SEQUENCE2');
xlabel ('---->n');
ylabel('---->b(n)');
c=conv (a, b)
n3=0:1:n1+n2-2;
subplot (2, 1, 2), stem (n3, c);
title ('CONVOLUTION OF TWO SEQUENCES');
xlabel ('---->n');
ylabel ('---->c (n)');

Output:

Enter the input sequence1= [2 3 4]


Enter the input sequence2= [1 2 3]
c=2 7 16 17 12
Enter the input sequence1= [2 3 4]
Enter the input sequence2= [1 2 3]
n1 = 3
n2 =3
c = 2 7 16 17 12

Result: Linear convolution of two discrete sequences is computed.

DIGITAL SIGNAL PROCESSING LAB 33


ELECTRONICS & COMMUNICATION ENGINEERING

Inference: The length of the Linear convolved sequence is n1+n2-1 where n1and
n2 are lengths of sequences.

Questions & Answers

1. What do you understand by Linear Convolution.


a. The convolution of discrete – time signals is known as discrete convolution. Let x
(n) be the input to an LTI system and y (n) be the output of the system. Let h (n) be
the response of the system to an impulse. The output y (n) can be obtained by
convolving the impulse response h (n) and the input signal x (n)

Y (n) = ∑ h( m) x ( n − m)
m = −∞
the above equation that gives the response y (n)

of an LTI system as a function of the input signal x (n) and the impulse response h
(n) is called a convolution sum.

2. What are the properties of convolution.


a. 1. Commutative property x (n) * h (n) = h (n) * x (n)
2. Associative property [x (n) * h1 (n)] * h2 (n) = x (n) * [h1 (n) * h2 (n)]
3. Distributive property X (n) * [h1 (n) + h2 (n)] = x (n) * h1 (n) + x (n) * h2 (n)].

DIGITAL SIGNAL PROCESSING LAB 34


ELECTRONICS & COMMUNICATION ENGINEERING

3. TO VERIFY CIRCULAR CONVOLUTION


Aim: To compute the circular convolution of two discrete sequences.
Theory: Two real N-periodic sequences x(n) and h(n) and their circular or periodic
convolution sequence y(n) is also an N- periodic and given by,

N −1
y (n) = ∑ h(m) x((n − m)) N , for n=0 to N-1.
m =0

Circular convolution is some thing different from ordinary linear convolution


operation, as this involves the index ((n-m))N, which stands for a ‘modula-N’
operation. Basically both type of convolution involve same six steps. But the
difference between the two types of convolution is that in circular convolution the
folding and shifting (rotating) operations are performed in a circular fassion by
computing the index of one of the sequences with ‘modulo-N’ operation. Either one of
the two sequences may be folded and rotated without changing the result of circular
convolution. That is,
N −1
y (n) = ∑ x (m)h((n − m)) N , for n=0 to (N-1).
m =0
If x (n) contain L no of samples and h (n) has M no of samples and that L > M, then
perform circular convolution between the two using N=max (L,M), by adding (L-M) no
of zero samples to the sequence h (n), so that both sequences are periodic with
number.
Two sequences x (n) and h (n), the circular convolution of these two sequences

can be found by using the following steps.

1. Graph N samples of h (n) as equally spaced points around an outer circle in


counterclockwise direction.

2. Start at the same point as h (n) graph N samples of x (n) as equally spaced
points around an inner circle in clock wise direction.

3. Multiply corresponding samples on the two circles and sum the products to
produce output.

4. Rotate the inner circle one sample at a time in counter clock wise direction
and go to step 3 to obtain the next value of output.

5. Repeat step No.4 until the inner circle first sample lines up with first sample of
the exterior circle once again.

DIGITAL SIGNAL PROCESSING LAB 35


ELECTRONICS & COMMUNICATION ENGINEERING

Program:
%circular convolution
a=input('enter the input sequence1=');
b=input('enter the input sequence2=');
n1=length (a)
n2=length (b)
n3=n1-n2
N=max (n1, n2);
if (n3>0)
b= [b, zeros (1, n1-n2)]
n2=length (b);
else
a= [a, zeros (1, N-n1)]
n1=length (a);
end;
k=max (n1, n2);
a=a';
b=b';
c=b;
for i=1: k-1
b=circshift (b, 1);
c=[c, b];
end;
disp(c);
z=c*a;
disp ('z=')
disp (z)
subplot (2, 2, 1);
stem (a,'filled');
title ('INPUT SEQUENCE1');
xlabel ('---->n');
ylabel ('---->Amplitude')
subplot (2, 2, 2);
stem (b,'filled');

DIGITAL SIGNAL PROCESSING LAB 36


ELECTRONICS & COMMUNICATION ENGINEERING

title ('INPUT SEQUENCE2');


xlabel ('---->n');
ylabel ('---->Amplitude');
subplot (2, 1, 2);
stem (z,'filled');
title ('CONVOLUTION OF TWO SEQUENCES');
xlabel ('---->n');
ylabel ('---->Amplitude');

Output:
Enter the input sequence1= [2 3 4 5]
Enter the input sequence2= [1 1 0]
n1 =4
n2 =3
n3 =1
b=
1 1 0 0
1 0 0 1
1 1 0 0
0 1 1 0
0 0 1 1

z=
7
5
7
9

DIGITAL SIGNAL PROCESSING LAB 37


ELECTRONICS & COMMUNICATION ENGINEERING

Result: Circular convolution of two discrete sequences is computed.

Inference: The length of the circularly convolved sequence is max (n1, n2) where
n1 and n2 are the lengths of given sequences.

Questions & Answers


1. Define circular convolution?
a. Let x1(n) and x2(n) are finite duration sequences both of length N with DFTs X1(k)
and x2(k).if X3(k)=X1(k)X2(k), then the sequence x3(n) can obtained by circular
N −1
convolution, defined as x3(n)= ∑ x (m) x
m =0
1 2 ((n − m)) N .

2. What do you understand by periodic convolution?


a. Let x1p (n) and x2p (n) with a period of N samples so that xp (n) =xp (n+lN); Then
discrete Fourier series of the sequence xp (n) is defined as Xp (k)
N −1
= ∑x
n =0
p (n)e − j 2Πkn / N

DIGITAL SIGNAL PROCESSING LAB 38


ELECTRONICS & COMMUNICATION ENGINEERING

4. DESIGN FIR FILTER (LP/HP) USING WINDOWING


TECHNIQUE
a) USING RECTANGULAR WINDOW

Aim: To design FIR high pass filter using rectangular window.

Theory: The design frequency response Hd (ejw) of a filter is periodic in frequency


and can be expanded in a Fourier series. The resultant series is given by


jw
Hd (e ) = ∑h (n)e
n=−∞
d
− jwn

Where
Π

Hd(n) = 1/ 2Π ∫ H (e jω )e jωn dω
−Π

and known as fourier coefficients having infinite length. One possible way of
obtaining FIR filter is to truncate the infinite fourier series at n = +/- [N-1/2], Where N
is the length of the desired sequence. But abrupt truncation of the Fourier series
results in oscillation in the passband and stopband. These oscillations are due to
slow convergence of the fourier series and this effect is known as the Gibbs
phenomenon. To reduce these oscillations, the Fourier coefficients of the filter are
modified by multiplying the infinite impulse response with a finite weighing sequence
ω (n) called a window.
where

ω (n) = ω (-n) ≠ 0 for |n| [ ≤ (N-1/2]/2]

=0 for |n|> (N-1/2]/2]


After multiplying window sequence ω (n) with hd (n), we get a finite duration
sequence h (n) that satisfies the desired magnitude response.

h (n) = hd(n) ω (n) for all |n| ≤ [N-1/2]

=0 for |n|> [N-1/2]


The frequency response H (ejw) so the filter can be obtained by convolution of Hd(eJW)
and W (ejw) given by

∫H
jθ j ( ω −θ )
H(ejw) = 1/ 2 Π d (e )W ( e dθ
−Π

Hd(ejw) * W (ejw)

Because both Hd (ejw) and W (ejw) are periodic function, the operation often called as
periodic convolution.

DIGITAL SIGNAL PROCESSING LAB 39


ELECTRONICS & COMMUNICATION ENGINEERING

The rectangular window sequence is given by

WR (n) = 1 for – (N-1/2 ≤ n ≤ (n-1)/2

= 0 otherwise

Program:

%Design of high pass filter using rectangular window


WC=0.5*pi;
N=25;
b=fir1 (N-1, wc/pi,'high', rectwin (N));
disp ('b=');
disp (b)
w=0:0.01: pi;
h=freqz (b, 1, w);
plot (w/pi, abs (h));
xlabel ('Normalised Frequency');
ylabel ('Gain in dB')
title ('FREQUENCY RESPONSE OF HIGHPASS FILTER USING
RECTANGULAR WINDOW');

Output:

b= Columns 1 through 17
-0.0000 0.0297 -0.0000 -0.0363 -0.0000 0.0467 -0.0000 -0.0654 -
0.0000 0.1090 -0.0000 -0.3269 0.5135 -0.3269 -0.0000 0.1090 -
0.0000
Columns 18 through 25
-0.0654 -0.0000 0.0467 -0.0000 -0.0363 -0.0000 0.0297 -0.0000

DIGITAL SIGNAL PROCESSING LAB 40


ELECTRONICS & COMMUNICATION ENGINEERING

Result: FIR high pass filter is designed by using rectangular window.

Inference: Magnitude response of FIR high pass filter designed using


Rectangular window as significant sidelobes.

Questions & Answers

1. What are "FIR filters"?

a. FIR filters are one of two primary types of digital filters used in Digital Signal

Processing (DSP) applications (the other type being IIR).

2. What does "FIR" mean?

a.” FIR" means "Finite Impulse Response".

DIGITAL SIGNAL PROCESSING LAB 41


ELECTRONICS & COMMUNICATION ENGINEERING

3. Why is the impulse response "finite"?

a. The impulse response is "finite" because there is no feedback in the filter; if you

put in an impulse (that is, a single "1" sample followed by many "0" samples),

zeroes will eventually come out after the "1" sample has made its way in the delay

line past all the coefficients.

4. How do you pronounce "FIR"?

a. Some people say the letters F-I-R; other people pronounce as if it were a type of

tree. We prefer the tree. (The difference is whether you talk about an F-I-R filter or

a FIR filter.)

5. What is the alternative to FIR filters?

a. DSP filters can also be "Infinite Impulse Response" (IIR). IIR filters use feedback,

so when you input an impulse the output theoretically rings indefinitely.

6. How do FIR filters compare to IIR filters?

a. Each has advantages and disadvantages. Overall, though, the advantages of FIR

filters outweigh the disadvantages, so they are used much more than IIRs.

7. What are the advantages of FIR Filters (compared to IIR filters)?

a. Compared to IIR filters, FIR filters offer the following advantages:

• They can easily be designed to be "linear phase" (and usually are).


Put simply, linear-phase filters delay the input signal, but don’t distort
its phase.
• They are simple to implement. On most DSP microprocessors, the
FIR calculation can be done by looping a single instruction.
• They are suited to multi-rate applications. By multi-rate, we mean
either "decimation" (reducing the sampling rate), "interpolation"
(increasing the sampling rate), or both. Whether decimating or
interpolating, the use of FIR filters allows some of the calculations to
be omitted, thus providing an important computational efficiency.

DIGITAL SIGNAL PROCESSING LAB 42


ELECTRONICS & COMMUNICATION ENGINEERING

In contrast, if IIR filters are used, each output must be individually


calculated, even if it that output will discarded (so the feedback will be
incorporated into the filter).

• They have desirable numeric properties. In practice, all DSP filters


must be implemented using "finite-precision" arithmetic, that is, a
limited number of bits. The use of finite-precision arithmetic in IIR
filters can cause significant problems due to the use of feedback, but
FIR filters have no feedback, so they can usually be implemented
using fewer bits, and the designer has fewer practical problems to
solve related to non-ideal arithmetic.
• They can be implemented using fractional arithmetic. Unlike IIR filters,
it is always possible to implement a FIR filter using coefficients with
magnitude of less than 1.0. (The overall gain of the FIR filter can be
adjusted at its output, if desired.) This is an important consideration
when using fixed-point DSP's, because it makes the implementation
much simpler.

8. What are the disadvantages of FIR Filters (compared to IIR filters)?

a. Compared to IIR filters, FIR filters sometimes have the disadvantage that they

require more memory and/or calculation to achieve a given filter response

characteristic. Also, certain responses are not practical to implement with FIR

filters.

9. What terms are used in describing FIR filters?

• Impulse Response - The "impulse response" of a FIR filter is actually


just the set of FIR coefficients. (If you put an "impulse" into a FIR filter
which consists of a "1" sample followed by many "0" samples, the
output of the filter will be the set of coefficients, as the 1 sample
moves past each coefficient in turn to form the output.)
• Tap - A FIR "tap" is simply a coefficient/delay pair. The number of FIR
taps, (often designated as "N") is an indication of 1) the amount of
memory required to implement the filter, 2) the number of calculations
required, and 3) the amount of "filtering" the filter can do; in effect,

DIGITAL SIGNAL PROCESSING LAB 43


ELECTRONICS & COMMUNICATION ENGINEERING
more taps means more stopband attenuation, less ripple, narrower
filters, etc.)

• Multiply-Accumulate (MAC) - In a FIR context, a "MAC" is the


operation of multiplying a coefficient by the corresponding delayed
data sample and accumulating the result. FIRs usually require one
MAC per tap. Most DSP microprocessors implement the MAC
operation in a single instruction cycle.
• Transition Band - The band of frequencies between passband and
stopband edges. The narrower the transition band, the more taps are
required to implement the filter. (A "small" transition band results in a
"sharp" filter.)
• Delay Line - The set of memory elements that implement the "Z^-1"
delay elements of the FIR calculation.
• Circular Buffer - A special buffer which is "circular" because
incrementing at the end causes it to wrap around to the beginning, or
because decrementing from the beginning causes it to wrap around to
the end. Circular buffers are often provided by DSP microprocessors
to implement the "movement" of the samples through the FIR delay-
line without having to literally move the data in memory. When a new
sample is added to the buffer, it automatically replaces the oldest one.

b) USING KAISER WINDOW

Aim: To design FIR low pass filter using Kaiser Window for different values of
Beeta and verify its characteristics.
Theory: The Kaiser window is given by

Wk (n) = Io [ α (1 − (2n / N − 1) 2 ) / I 0 (α ) ] for |n| ≤ N-1/2


=0 otherwise

Where α is an independent parameter.

Io (x) is the zeroth order Bessel function of the first kind

I0(x) = 1+ ∑[1 / k! (x/2) ]


k =1
k 2

DIGITAL SIGNAL PROCESSING LAB 44


ELECTRONICS & COMMUNICATION ENGINEERING

Advantages of Kaiser Window

1. It provides flexibility for the designer to select the side lobe level and N.
2. It has the attractive property that the side lobe level can be varied
continuously from the low value in the Blackman window to the high value
in the rectangular window.

Program:
%Design of FIR lowpass filter using Kaiser Window
WC=0.5*pi;
N=25;
b=fir1 (N, wc/pi, kaiser (N+1, 0.5))
w=0:0.01: pi;
h=freqz (b, 1, w);
plot (w/pi, 20*log10 (abs (h)));
hold on
b=fir1 (N, wc/pi, kaiser (N+1, 3.5))
w=0:0.01: pi;
h=freqz (b, 1, w);
plot (w/pi, 20*log10 (abs (h)));
hold on
b=fir1 (N, wc/pi, kaiser (N+1, 8.5))
w=0:0.01: pi;
h=freqz (b, 1, w);
plot (w/pi, 20*log10 (abs (h)));
xlabel ('Normalised Frequency');
ylabel ('Magnitude in dB');
title ('FREQUENCY RESPONSE OF LOWPASS FILTER USING
KAISER WINDOW');
hold off

Output:
b = Columns 1 through 17
0.0170 -0.0186 -0.0206 0.0229 0.0258 -0.0294 -0.0341 0.0405
0.0497 -0.0641 -0.0899 0.1501 0.4507 0.4507 0.1501 -0.0899 -
0.0641

DIGITAL SIGNAL PROCESSING LAB 45


ELECTRONICS & COMMUNICATION ENGINEERING

Columns 18 through 26
0.0497 0.0405 -0.0341 -0.0294 0.0258 0.0229 -0.0206 -0.0186
0.0170
b = Columns 1 through 17
0.0024 -0.0041 -0.0062 0.0089 0.0124 -0.0169 -0.0227 0.0305
0.0412 -0.0573 -0.0849 0.1471 0.4496 0.4496 0.1471 -0.0849 -
0.0573
Columns 18 through 26
0.0412 0.0305 -0.0227 -0.0169 0.0124 0.0089 -0.0062 -0.0041
0.0024
b = Columns 1 through 17
0.0000 -0.0002 -0.0006 0.0015 0.0032 -0.0062 -0.0109 0.0182
0.0293 - 0.0467 -0.0766 0.1416 0.4473 0.4473 0.1416 -0.0766 -
0.0467
Columns 18 through 26
0.0293 0.0182 -0.0109 -0.0062 0.0032 0.0015 -0.0006 -0.0002
0.0000

DIGITAL SIGNAL PROCESSING LAB 46


ELECTRONICS & COMMUNICATION ENGINEERING

Result: FIR low pass filter is designed by using Kaiser Window for different values
of Beeta.
Inference: The response of stop band improves as beeta increases.
Questions & Answers

1. What are the design techniques of designing FIR filters?


a. There are three well-known methods for designing FIR filters with linear
phase.These are (1) window method (2) frequency sampling method (3) optimal or
minimax design.
2. What is the reason that FIR filter is always stable?
a. FIR filter is always stable because all its poles are at the origin.
3. What are the properties of FIR filter?
• FIR filter is always stable.
• A realizable filter can always be obtained.
• FIR filter has a linear phase response.

DIGITAL SIGNAL PROCESSING LAB 47


ELECTRONICS & COMMUNICATION ENGINEERING

5. DESIGN IIR FILTER (LP/HP)


a)

Aim: To design IIR Butterworth low pass filter and verify its characteristics.

Theory: The most common technique used for designing IIR digital filters known
as indirect method, involves first designing an analog prototype filter and then
transforming the prototype to a digital filter. For the given specifications of a digital
filter, the derivation of the digital filter transfer function requires three steps.
1. Map the desired digital filter specifications into those for an equivalent
analog filter.
2. Derive the analog transfer function for the analog prototype.
3. Transform the transfer function of the analog prototype into an equivalent
digital filter transfer function.

There are several methods that can be used to design digital filters having an infinite
during unit sample response. The techniques described are all based on converting
an analog filter into digital filter. If the conversion technique is to be effective, it
should posses the following desirable properties.
1. The jΩ-axis in the s-plane should map into the unit circle in the z-plane.
Thus there will be a direct relationship between the two frequency
variables in the two domains.
2. The left-half plane of the s-plane should map into the inside of the unit
circle in the z-plane. Thus a stable analog filter will be converted to a
stable digital filter.
Design a digital filter using impulse invariance method
1. For the given specifications, find Ha (s), the transfer function of an analog
filter.
2. Select the sampling rate of the digital filter, T seconds per sample.
3. Express the analog filter transfer function as the sum of single-pole filters.
N

Ha (s) = ∑
K =1
ck / s − p k

DIGITAL SIGNAL PROCESSING LAB 48


ELECTRONICS & COMMUNICATION ENGINEERING

4. Compute the z-transform of the digital filter by using the formula


N


pkT
H (z) =
ck /1 − e z −1
K =1

For high sampling rates use


N

H (z) = ∑
pkT
Tc k /1 − e z −1
K =1

Design digital filter using bilinear transform technique.


1. From the given specifications, find prewarping analog frequencies using formula
Ω= 2/T tan w/2.
2. Using the analog frequencies find H (s) of the analog filter.

3. Select the sampling rate of the digital filter, call it T seconds per sample.

4. Substitute s= 2/T (1-z-1/1+ z-1) into the transfer function found in step2.

Program:
%Design of IIR Butterworth lowpass filter
alphap=input ('enter the pass band attenuation=');
alphas=input ('enter the stop band attenuation=');
fp=input ('enter the passband frequency=');
fs=input ('enter the stop band frequency=');
F=input ('enter the sampling frequency=');
omp=2*fp/F;
oms=2*fs/F;
[n, wn]=buttord (omp, oms, alphap, alphas)
[b, a]=butter (n, wn)
w=0:0.1: pi;
[h, ph]=freqz (b, a, w);
m=20*log (abs (h));
an=angle (h);
subplot (2, 1, 1);

DIGITAL SIGNAL PROCESSING LAB 49


ELECTRONICS & COMMUNICATION ENGINEERING

plot (ph/pi, m);


grid on;
ylabel ('Gain in dB');
xlabel ('Normalised Frequency');
title (‘FREQUENCY RESPONSE OF BUTTERWORTH LOWPASS
subplot (2, 1, 2);
title (‘PHASE RESPONSE OF BUTTERWORTH LOWPASS FILTER’);
plot (ph/pi, an);
grid on;
ylabel ('Phase in Radians');
xlabel ('Normalised Frequency');
Output:
Enter the pass band attenuation=0.4
Enter the stop band attenuation=60
Enter the pass band frequency=400
Enter the stop band frequency=800
Enter the sampling frequency=2000
n=6
Wn =0.4914
b =0.0273 0.1635 0.4089 0.5452 0.4089 0.1635 0.0273
a = 1.0000 -0.1024 0.7816 -0.0484 0.1152 -0.0032 0.0018

DIGITAL SIGNAL PROCESSING LAB 50


ELECTRONICS & COMMUNICATION ENGINEERING

Result: IIR Butterworth low pass filter is designed.

Inference: There are no ripples in the passband and stopband.

Questions & Answers


1. What are the advantages of IIR filters (compared to FIR filters)? What are IIR

filters? What does "IIR" mean?

a. IIR filters are one of two primary types of digital filters used in Digital Signal

Processing (DSP) applications (the other type being FIR). "IIR" means "Infinite

Impulse Response".

2. Why is the impulse response "infinite"?

a. The impulse response is "infinite" because there is feedback in the filter; if you put

in an impulse (a single "1" sample followed by many "0" samples), an infinite

number of non-zero values will come out (theoretically).

3. What is the alternative to IIR filters?

a. DSP filters can also be "Finite Impulse Response" (FIR). FIR filters do not use

feedback, so for a FIR filter with N coefficients, the output always becomes zero

after putting in N samples of an impulse response.IIR filters can achieve a given

filtering characteristic using less memory and calculations than a similar FIR filter.

4. What are the disadvantages of IIR filters (compared to FIR filters)?

• They are more susceptible to problems of finite-length arithmetic, such


as noise generated by calculations, and limit cycles. (This is a direct
consequence of feedback: when the output isn't computed perfectly
and is fed back, the imperfection can compound.)
• They are harder (slower) to implement using fixed-point arithmetic.
• They don't offer the computational advantages of FIR filters for
multirate (decimation and interpolation) applications.

DIGITAL SIGNAL PROCESSING LAB 51


ELECTRONICS & COMMUNICATION ENGINEERING

b)

Aim: To design IIR Chebyshew type I high pass filter.

Program:
%Design of IIR Chebyshew type I high pass filter
alphap=input ('enter the pass band attenuation=');
alphas=input ('enter the stop band attenuation=');
fp=input ('enter the pass band frequency=');
fs=input ('enter the stop band frequency=');
F=input ('enter the sampling frequency=');
omp=2*fp/F;
oms=2*fs/F;
[n, wn]=cheb1ord (omp, oms, alphap, alphas)
[b, a]=cheby1 (n, wn, high)
w=0:0.1: pi;
[h, ph]=freqz (b, a, w);
m=20*log (abs (h));
an=angle (h);
subplot (2, 1, 1);
plot (ph/pi, m);
grid on;
ylabel ('Gain in dB');
xlabel ('Normalised Frequency');
title (‘FREQUENCY RESPONSE OF CHEBYSHEW TYPE I HIGH PASS FILTER’);
subplot (2, 1, 2);
plot (ph/pi, an);
grid on;
ylabel ('Phase in Radians');
xlabel ('Normalised Frequency');
title (‘PHASE RESPONSE OF CHEBYSHEW TYPE I HIGH PASS FILTER’);

DIGITAL SIGNAL PROCESSING LAB 52


ELECTRONICS & COMMUNICATION ENGINEERING

Output:
enter the pass band attenuation=1
enter the stop band attenuation=15
enter the passband frequency=0.2*pi
enter the stop band frequency=0.1*pi
n=3
Wn =0.2000
b = 0.4759 -1.4278 1.4278 -0.4759
a = 1.0000 -1.6168 1.0366 -0.1540

Result: IIR Chebyshew type I high pass filter is designed on DSP Processors.

Inference: The transition band is less in Chebyshev filter compared to Butterworth


filter.

DIGITAL SIGNAL PROCESSING LAB 53


ELECTRONICS & COMMUNICATION ENGINEERING

Questions & Answers


1. What are the parameters that can be obtained from the Chebyshev filter
specifications?
a. From the given Chebyshev filter specifications we can obtain the parameters like
the order of the filter N, є, transition ratio k, and the poles of the filter.

2. Distinguish between Butterworth and Chebyshev (type-I) filter?


• The magnitude response of Butterworth filter decreases monotonically as the
frequency Ω increases from 0 to ∞, where as the magnitude response of the
Chebyshev filter exhibits ripple in the passband and monotonically decreasing
in the stopband.
• The transition band is more in Butterworth filter compared to Chebyshev filter.
• The poles of the Butterworth filter lies on a circle whereas the poles of the
Chebyshev filter lies on an ellipse.
• For the same specifications the number of poles in Butterworth filter is more
when compared to Chebyshev filter, i.e., the order of the Chebyshev filter is
less than that of Butterworth.

DIGITAL SIGNAL PROCESSING LAB 54


ELECTRONICS & COMMUNICATION ENGINEERING

6. N-POINT FFT ALGORITHM


Aim: To determine the N-point FFT of a given sequence.

Theory: The Fast Fourier transform is a highly efficient procedure for computing
the DFT of a finite series and requires less no of computations than that of direct
evaluation of DFT. It reduces the computations by taking the advantage of the fact
that the calculation of the coefficients of the DFT can be carried out iteratively. Due to
this, FFT computation technique is used in digital spectral analysis, filter simulation,
autocorrelation and pattern recognition. The FFT is based on decomposition and
breaking the transform into smaller transforms and combining them to get the total
transform. FFT reduces the computation time required to compute a discrete Fourier
transform and improves the performance by a factor 100 or more over direct
evaluation of the DFT. The fast fourier transform algorithms exploit the two basic
/2
properties of the twiddle factor (symmetry property: w Nk + N = − w Nk ,

periodicity property: w Nk + N = w Nk ) and reduces the number of complex


2
multiplications required to perform DFT from N to N/2 log2N. In other words, for

N=1024, this implies about 5000 instead of 106 multiplications – a reduction factor of
200. FFT algorithms are based on the fundamental principal of decomposing the
computation of discrete fourier transform of a sequence of length N into successively
smaller discrete fourier transform of a sequence of length N into successively smaller
discrete fourier transforms. There are basically two classes of FFT algorithms. They
are decimation-in-time and decimation-in-frequency. In decimation-in-time, the
sequence for which we need the DFT is successively divided into smaller sequences
and the DFTs of these subsequences are combined in a certain pattern to obtain the
required DFT of the entire sequence. In the decimation-in-frequency approach, the
frequency samples of the DFT are decomposed into smaller and smaller
subsequences in a similar manner.

Radix – 2 DIT – FFT algorithm

1. The number of input samples N=2M , where, M is an integer.


2. The input sequence is shuffled through bit-reversal.
3. The number of stages in the flow graph is given by M=log2 N.
4. Each stage consists of N/2 butterflies.

DIGITAL SIGNAL PROCESSING LAB 55


ELECTRONICS & COMMUNICATION ENGINEERING

5. Inputs/outputs for each butterfly are separated by 2m-1 samples, where m


represents the stage index, i.e., for first stage m=1 and for second stage m=2
so on.
6. The no of complex multiplications is given by N/2 log2 N.
7. The no of complex additions is given by N log2 N.
8. The twiddle factor exponents are a function of the stage index m and is given
Nt
by k= m
t = 0,1,2,...2 m −1 − 1.
2
9. The no of sets or sections of butterflies in each stage is given by the formula
2M-m.
10. The exponent repeat factor (ERF), which is the number of times the exponent
sequence associated with m is repeated is given by 2M-m.
Radix – 2 DIF – FFT Algorithm

1. The number of input samples N=2M, where M is number of stages.


2. The input sequence is in natural order.
3. The number of stages in the flow graph is given by M=log2 N.
4. Each stage consists of N/2 butterflies.
5. Inputs/outputs for each butterfly are separated by 2M-m samples, Where m
represents the stage index i.e., for first stage m=1 and for second stage m=2
so on.
6. The number of complex multiplications is given by N/2 log2 N.
7. The number of complex additions is given by N log2 N.
8. The twiddle factor exponents are a function of the stage index m and is given
N
by k = t
M − m +1
, t = 0,1,2,...2 m − m − 1.
2
9. The number of sets or sections of butterflies in each stage is given by the
formula 2m-1.
10. The exponent repeat factor (ERF), which is the number of times the
exponent sequence associated with m repeated is given by 2m-1.
For decimation-in-time (DIT), the input is bit-reversed while the output is in natural
order. Whereas, for decimation-in-frequency the input is in natural order while the
output is bit reversed order.
The DFT butterfly is slightly different from the DIT wherein DIF the complex
multiplication takes place after the add-subtract operation.

DIGITAL SIGNAL PROCESSING LAB 56


ELECTRONICS & COMMUNICATION ENGINEERING

Both algorithms require N log2 N operations to compute the DFT. Both algorithms
can be done in-place and both need to perform bit reversal at some place during the
computation.
Program:
% N-point FFT algorithm
N=input ('enter N value=');
Xn=input ('type input sequence=');
k=0:1: N-1;
L=length (xn)
if (N<L)
error ('N MUST BE>=L');
end;
x1= [xn zeros (1, N-L)]
for c=0:1:N-1;
for n=0:1:N-1;
p=exp (-i*2*pi*n*C/N);
x2(c+1, n+1) =p;
end;
Xk=x1*x2';
end;
MagXk=abs (Xk);
angXk=angle (Xk);
subplot (2, 1, 1);
stem (k, magXk);
title ('MAGNITUDE OF DFT SAMPLES');
xlabel ('---->k');
ylabel ('-->Amplitude');
subplot (2, 1, 2);
stem (k, angXk);
title ('PHASE OF DFT SAMPLES');
xlabel ('---->k');
ylabel ('-->Phase');
disp (‘abs (Xk) =');
disp (magXk)
disp ('angle=');
disp (angXk)

DIGITAL SIGNAL PROCESSING LAB 57


ELECTRONICS & COMMUNICATION ENGINEERING

Output:
enter N value=5
type input sequence= [1 1 0]
L= 3
x1 = 1 1 0 0 0
abs (Xk) = 2.0000 1.6180 0.6180 0.6180 1.6180
angle= 0 0.6283 1.2566 -1.2566 -0.6283

Result: N-point FFT of a given sequence is determined.

Inference: FFT reduces the computation time required to compute discrete


Fourier transform

DIGITAL SIGNAL PROCESSING LAB 58


ELECTRONICS & COMMUNICATION ENGINEERING

Questions & Answers

1. What are the applications of FFT algorithms?


a. The applications of FFT algorithm includes
• Linear filtering
• Correlation
• Spectrum analysis.
2. What is meant by radix-2 FFT?
a. The FFT algorithm is most efficient in calculating N- point DFT. If the number of
output points N can be expressed as a power of 2, that is, N=2 M, where M is an
integer, then this algorithm is known as radix -2 FFT algorithm.

3. What is an FFT "radix"?

a. The "radix" is the size of FFT decomposition. In the example above, the radix was
2. For single-radix FFT's, the transform size must be a power of the radix. In the
example above, the size was 32, which is 2 to the 5th power.

4. What are "twiddle factors"?

a. "Twiddle factors" are the coefficients used to combine results from a previous

stage to form inputs to the next stage.

5. What is an "in place" FFT?

a. An "in place" FFT is simply an FFT that is calculated entirely inside its original

sample memory. In other words, calculating an "in place" FFT does not require

additional buffer memory (as some FFT's do.)

6. What is "bit reversal"?

a. "Bit reversal" is just what it sounds like: reversing the bits in a binary word from left
to write. Therefore the MSB's become LSB's and the LSB's become MSB's. But what
does that have to do with FFT's? Well, the data ordering required by radix-2 FFT's
turns out to be in "bit reversed" order, so bit-reversed indexes are used to combine
FFT stages. It is possible (but slow) to calculate these bit-reversed indices in
software; however, bit reversals are trivial when implemented in hardware. Therefore,

DIGITAL SIGNAL PROCESSING LAB 59


ELECTRONICS & COMMUNICATION ENGINEERING

almost all DSP processors include a hardware bit-reversal indexing capability (which
is one of the things that distinguishes them from other microprocessors.)

7. What is "decimation in time" versus "decimation in frequency"?

a. FFT's can be decomposed using DFT's of even and odd points, which is called a
Decimation-In-Time (DIT) FFT, or they can be decomposed using a first-half/second-
half approach, which is called a "Decimation-In-Frequency" (DIF) FFT. Generally, the
user does not need to worry which type is being used.

DIGITAL SIGNAL PROCESSING LAB 60


ELECTRONICS & COMMUNICATION ENGINEERING

7. MATLAB PROGRAM TO GENERATE SUM OF SINUSOIDAL


SIGNALS

Aim: To generate sum of sinusoidal signals.

Theory:
Sinusoidal sequence:

X (n) = cos (w0n + θ ), ∀n

Where θ is the phase in radians. A MATLAB function cos (or sin) is used to
generate sinusoidal sequences.

Signal addition: This is a sample-by-sample addition given by

{X1 (n)} + {x2(n)} = {x1(n) + x2(n)}

It is implemented in Matlab by the arithmetic operator ‘’+’’. However, the lengths of


x1 (n) and x2 (n) must be the same. If sequences are of unequal lengths, or if the
sample positions are different 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 (and hence the same length). This requires careful attention
to MATLab’s indexing operations. In particular, logical operation of intersection ‘’&’’
relational operations like ‘’<=’’ and ‘’==’’ and the find function are required to make
x1(n) amd x2 (n) of equal length.

Program:
%Generation of sum of sinusoidal sequences
n=-4:0.5:4;
y1=sin (n)
subplot (2, 2, 1)
stem (n, y1,'filled')
grid on;
xlabel ('-->Samples');
ylabel ('--->Magnitude');
title ('SINUSOIDAL SIGNAL1');
y2=sin (2*n)
subplot (2, 2, 2)
stem (n, y2,'filled')
grid on;

DIGITAL SIGNAL PROCESSING LAB 61


ELECTRONICS & COMMUNICATION ENGINEERING

xlabel ('-->Samples');
ylabel ('--->Magnitude');
title ('SINUSOIDAL SIGNAL2');
y3=y1+y2
subplot (2, 1, 2);
stem (n, y3,'filled');
xlabel ('-->Samples');
ylabel ('--->Magnitude');
title ('SUM OF SINUSOIDAL SIGNALS');
Output:
y1 = 0.7568 0.3508 -0.1411 -0.5985 -0.9093 -0.9975 -0.8415 -
0.4794
0 0.4794 0.8415 0.9975 0.9093 0.5985 0.1411 -0.3508 -
0.7568
y2 = -0.9894 -0.6570 0.2794 0.9589 0.7568 -0.1411 -0.9093 -
0.8415
0 0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794 0.6570
0.9894
y3 =-0.2326 -0.3062 0.1383 0.3605 -0.1525 -1.1386 -1.7508 -
1.3209
0 1.3209 1.7508 1.1386 0.1525 -0.3605 -0.1383 0.3062
0.2326

DIGITAL SIGNAL PROCESSING LAB 62


ELECTRONICS & COMMUNICATION ENGINEERING

Result: Sum of sinusoidal signals is generated.

Inference: The lengths of x1 (n) and x2 (n) must be the same for sample-by-
sample addition.

Questions & Answers


1. What is deterministic signal? Give example.
a. A deterministic signal is a signal exhibiting no uncertainty of value at any given
instant of time. Its instantaneous value can be accurately predicted by specifying a
formula, algorithm or simply its describing statement in words.
Example; v (t) =Ao sinwt

2. Define a periodic signal?


a. A signal x (n) is periodic with period N if and only if x (n+N) =x (n) for all n.

DIGITAL SIGNAL PROCESSING LAB 63


ELECTRONICS & COMMUNICATION ENGINEERING

8. MATLAB PROGRAM TO FIND FREQUENCY RESPONSE OF


ANALOG LP/HP FILTERS.

a)

Aim: To find frequency response of Butterworth analog low pass filter.

Theory: The magnitude function of the butterworth lowpass filter is given by

H ( jΩ) = 1 /[1 + (Ω / Ω c ) 2 N ]1 / 2 N = 1, 2, 3,
Where N is the order of the filter and Ωc is the cutoff frequency.
The following expression is used for the order of the filter.

0 . 1α
10 S
−1
log 0 . 1α
N = 10 P
−1
Ω S
log
Ω P
Two properties of Butterworth lowpass filter

1. The magnitude response of the butterworth filter decreases


monotonically as the frequency Ω increases from 0 to ∞.
2. The magnitude response of the butterworth filter closely approximates
the ideal response as the order N increases.
3. The poles of the Butterworth filter lies on a circle.
Steps to design an analog butterworth lowpass filter
1. From the given specifications find the order of the filter N.
2. Round off it to the next higher integer.
3. Find the transfer function H (s) for Ωc = 1 rad/sec for the value of N.
4. Calculate the value of cutoff frequency Ωc.
5. Find the transfer function Ha (s) for the above value of Ωc by substituting
s s/Ωc in H(s).
Program:
%Design of Butterworth lowpass filter
alphap=input ('enter the pass band attenuation=');
alphas=input ('enter the stop band attenuation=');
fp=input ('enter the passband frequency=');
fs=input ('enter the stop band frequency=');
F=input ('enter the sampling frequency=');
omp=2*fp/F;

DIGITAL SIGNAL PROCESSING LAB 64


ELECTRONICS & COMMUNICATION ENGINEERING

oms=2*fs/F;
[N, wn]=buttord (omp, oms, alphap, alphas,'s')
[b, a]=butter (n, wn)
w=0:0.01: pi;
[h, ph]=freqz (b, a, w);
m=20*log (abs (h));
an=angle (h);
subplot (2, 1, 1);
plot (ph/pi, m);
grid on;
ylabel ('Gain in dB');
xlabel ('Normalised Frquency');
title ('FREQUENCY RESPONSE OF BUTTERWORTH LOWPASS FILTER');
subplot (2, 1, 2);
plot (ph/pi, an);
grid on;
ylabel ('Phase in Radians');
xlabel ('Normalisd Frequency');
title ('PHASE RESPONSE OF BUTTERWORTH LOWPASS FILTER');

Output:
Enter the pass band attenuation=0.4
Enter the stop band attenuation=60
Enter the pass band frequency=400
Enter the stop band frequency=800
Enter the sampling frequency=2000
n = 12
Wn = 0.4499
b = 0.0003 0.0040 0.0220 0.0735 0.1653 0.2644 0.3085
0.2644
0.1653 0.0735 0.0220 0.0040 0.0003
a = 1.0000 -1.1997 2.2442 -1.7386 1.5475 -0.7945 0.4106
-0.1362
0.0412 -0.0080 0.0013 -0.0001 0.0000

DIGITAL SIGNAL PROCESSING LAB 65


ELECTRONICS & COMMUNICATION ENGINEERING

Result: Butterworth analog low pass filter is designed and its frequency response
is found.

Inference: The magnitude response of the butterworth filter decreases


monotonically as the frequency increases.

Questions & Answers


1. Give any two properties of Butterworth lowpass filters?
• The magnitude response of the Butterworth filter decreases monotonically as
the frequency Ω increases from 0 to ∞ .
• The magnitude response of the Butterworth filter closely approximates the
ideal response as the order N increases.
• The poles of the Butterworth filter lies on a circle

DIGITAL SIGNAL PROCESSING LAB 66


ELECTRONICS & COMMUNICATION ENGINEERING

b)

Aim: To find frequency response of Chebyshew type I analog high pass Filter.

Theory: There are two types of Chebyshev filters. Type I Chebyshev filters are all-
pole filters that exhibits equiripple behaviour in the passband and a monotonic
characteristics in the stopband. On the other hand, the family of type II Chebyshev
filter contains both poles and zeros and exhibits a monotonic behaviour in the
passband and equiripple behaviour in the stopband.

The magnitude square response of Nth order type I filter can be expressed as

|H(jΩ) |2 = 1/1+є2C2N [Ω/Ωp] N = 1, 2,----

Where є is a parameter of the filter related to the ripple in the passband and CN (x) is
the Nth order Chebyshev polynomial defined as

CN (x) = cos (N cos-1 x), |x| ≤ 1 (passband)

And
CN (x) = cosh (N cosh-1 x), |x| > 1 (stopband)

Steps to design an analog Chebyshev lowpass filter

1. From the given specifications find the order of the filter N.


2. Round off it to the next higher integer.
3. Using the following formulas find the value of a and b, which are minor and
major axis of the ellipse respectively.
a = Ωp [µ1/N - µ-1/N]

2 ;

b=Ωp [µ1/N - µ-1/N]

Where µ = є-1 + є-2 + 1

Є= 100.1 α p - 1

Ωp = passband frequency

DIGITAL SIGNAL PROCESSING LAB 67


ELECTRONICS & COMMUNICATION ENGINEERING

α p = Maximum allowable attenuation in the passband


(For normalized Chebyshev filter Ωp = 1 rad/sec)

4. Calculate the poles of Chebyshev filter which lies on an ellipse by using the
formula.
Sk = a cosФk + jb sin Фk k= 1, 2, .N

Where Фk = Π /2 + [2k-1/2N] Π k= 1, 2, .N

5. Find the denominator polynominal of the transfer function using above poles.
6. The numerator of the transfer function depends on the value of N.
a) For N odd substitute s = 0 in the denominator polynominal and find
the value. This value is equal to the numerator of the transfer
function.
(For N odd the magnitude response |H(jΩ)| starts at 1.)

b) For N even substitute s=0 in the denominator polynominal and divide


the result by 1+ Є2. This value is equal to the numerator.

The order N of Chebyshev filter is given by

N= cos h-1 [(100.1 α s -1)/ (100.1 α p -1)]/cos h-1 ( Ω s/ Ω p)


Where α s is stopband attenuation at stopband frequency Ω s and α p is passband
attenuation at passband frequency Ω p . The major minor axis of the ellipse is given
by
b= Ω p [(µ1/N + µ-1/N )/2] and a = Ω p [ (µ1/N - µ-1/N )/2]

Where µ = Є-1 + 1+ Є-2


And Є = (100.1 α p -1)
Program:
%Design of IIR Chebyshew type I high pass filter
alphap=input ('enter the pass band attenuation=');
alphas=input ('enter the stop band attenuation=');
wp=input ('enter the pass band frequency=');
ws=input ('enter the stop band frequency=');
[n, wn]=cheb1ord (wp/pi, ws/pi, alphap, alphas,'s')
[b, a]=cheby1 (n, alphap, wn,'high')
w=0:0.01: pi;
[h, ph]=freqz (b, a, w);
m=20*log (abs (h));
an=angle (h);

DIGITAL SIGNAL PROCESSING LAB 68


ELECTRONICS & COMMUNICATION ENGINEERING

subplot (2, 1, 1);


plot (ph/pi, m);
grid on;
ylabel ('Gain in dB');
xlabel ('Normalised Frquency');
title ('FREQUENCY RESPONSE OF CHEBYSHEW TYPE I HIGHPASS
FILTER');
subplot (2, 1, 2);
plot (ph/pi, an);
grid on;
ylabel ('Phase in Radians');
xlabel ('Normalisd Frequency');
title ('PHASE RESPONSE OF CHEBYSHEW TYPE I HIGHPASS FILTER');

Output:

Enter the pass band attenuation=1


Enter the stop band attenuation=15
Enter the pass band frequency=0.2*pi
Enter the stop band frequency=0.1*pi
n =3
wn = 0.2000
b =0.4759 -1.4278 1.4278 -0.4759
a = 1.0000 -1.6168 1.0366 -0.1540

DIGITAL SIGNAL PROCESSING LAB 69


ELECTRONICS & COMMUNICATION ENGINEERING

Result: Chebyshew type I analog high pass filter is designed and its frequency
response is observed.

Inference: Chebyshev approximation provides better characteristics near the


cutoff frequency and near the stop band edge.

Questions & Answers


1. How one can design digital filters from analog filters?
• Map the desired digital filter specifications into those for an equivalent analog
filter.
• Derive the analog transfer function for the analog prototype.
• Transform the transfer function of the analog prototype into an equivalent
digital filter transfer function.
2. What are the properties of Chebyshev filter?
• The magnitude response of the Chebyshev filter exhibits ripple either in
passband or in stopband according to type.
• The poles of the Chebyshev filter lies on ellipse.

DIGITAL SIGNAL PROCESSING LAB 70


ELECTRONICS & COMMUNICATION ENGINEERING

9. POWER DENSITY SPECTRUM OF A SEQUENCE

Aim: To compute power density spectrum of a sequence.

Theory: PSD Power Spectral Density estimate.


Pxx = PSD(X, NFFT, Fs, WINDOW) estimates the Power Spectral Density of
a discrete-time signal vector X using Welch's averaged, modifiedperiodogram
method.X is divided into overlapping sections, each of which is detrended (according
to the detrending flag, if specified), then windowed by the WINDOW parameter, then
zero-padded to length NFFT. The magnitude squared of the length NFFT DFTs of
the sections are averaged to form Pxx. Pxx is length NFFT/2+1 for NFFT even,
(NFFT+1)/2 for NFFT odd, or NFFT if the signal X is complex. If you specify a scalar
for WINDOW, a Hanning window of that length is used. Fs is the sampling frequency
which doesn't affect the spectrum estimate but is used for scaling the X-axis of the
plots. [Pxx, F] = PSD(X, NFFT, Fs, WINDOW, NOVERLAP) returns a vector of
frequencies the same size as Pxx at which the PSD is estimated, and overlaps
the sections of X by NOVERLAP samples. [Pxx, Pxxc, F] = PSD(X, NFFT, Fs,
WINDOW, NOVERLAP, P) where P is a scalar between 0 and 1, returns the P*100%
confidence interval for Pxx. PSD(X, DFLAG), where DFLAG can be 'linear', 'mean' or
'none', specifies a detrending mode for the prewindowed sections of X. DFLAG can
take the place of any parameter in the parameter list (besides X) as long as it is last,
e.g. PSD(X,'mean'); PSD with no output arguments plots the PSD in the current
figure window, with confidence intervals if you provide the P parameter. The default
values for the parameters are NFFT = 256 (or LENGTH(X), whichever is smaller),
NOVERLAP = 0, WINDOW = HANNING (NFFT), Fs = 2, P = .95, and DFLAG =
'none'. You can obtain a default parameter by leaving it off or inserting an empty
matrix [], e.g. PSD(X, [], 10000).
Program:
%Power density spectrum of a sequence
x=input ('enter the length of the sequence=');
y=input ('enter the sequence=');
fs=input ('enter sampling frequency=');
N=input ('enter the value of N=');
q=input ('enter the window name1=');
m=input ('enter the window name2=');
s=input ('enter the window name3=');
pxx1=psd(y, N, fs, q)

DIGITAL SIGNAL PROCESSING LAB 71


ELECTRONICS & COMMUNICATION ENGINEERING

plot (pxx1,'c');
hold on;
grid on;
pxx2=psd(y, N, fs, m)
plot (pxx2,'k');
hold on;
pxx3=psd(y, N, fs, s)
plot (pxx3,'b');
hold on;
xlabel ('-->Frequency');
ylabel ('-->Magnitude');
title ('POWER SPECTRAL DENSITY OF A SEQUENCE');
hold off;

Output:
Enter the length of the sequence=5
Enter the sequence= [1 2 3 4 5]
Enter sampling frequency=20000
Enter the value of N=4
Enter the window name1=rectwin (N)

Enter the window name2=Kaiser (N, 4.5)


Enter the window name3=triang (N)

pxx1 =25.0000
2.0000
1.0000
pxx2 =14.2828
5.7258
0.3065
pxx3 = 20.0000
3.4000
0.0000

DIGITAL SIGNAL PROCESSING LAB 72


ELECTRONICS & COMMUNICATION ENGINEERING

Result: Power density spectrum of a sequence is computed.

Inference: Power spectral density does not have any phase information.

Questions & Answers


1. Define power spectral density?

a. The power spectral density is a measure of how the power in a signal changes
over frequency.

2. What is window function? What are the applications of window functions?


a. In signal processing, a window function is a function that is zero-valued outside of
some chosen interval. For instance, a function that is constant inside the interval
and zero elsewhere is called a rectangular window, which describes the shape of
its graphical representation. When another function or a signal (data) is multiplied
by a window function, the product is also zero-valued outside the interval.
Applications of window functions include spectral analysis, filter design and beam
forming.

DIGITAL SIGNAL PROCESSING LAB 73


ELECTRONICS & COMMUNICATION ENGINEERING

10. FFT OF A GIVEN 1-D SIGNAL

Aim: To find the FFT of a given 1-D signal and plot the characteristics.

Theory: The DFT of a sequence can be evaluated using the formula


N −1
X (k ) = ∑ x(n)e − j 2πnk / N 0 ≤ k ≤ N - 1
n =0

Substituting W N = e − j 2π / N , we have
N −1
X (k ) = ∑ x (n)W Nnk 0 ≤ k ≤ N - 1
n =0

The Fast Fourier transform is a highly efficient procedure for computing the DFT of a
finite series and requires less no of computations than that of direct evaluation of
DFT. It reduces the computations by taking the advantage of the fact that the
calculation of the coefficients of the DFT can be carried out iteratively. Due to this,
FFT computation technique is used in digital spectral analysis, filter simulation,
autocorrelation and pattern recognition. The FFT is based on decomposition and
breaking the transform into smaller transforms and combining them to get the total
transform. FFT reduces the computation time required to compute a discrete Fourier
transform and improves the performance by a factor 100 or more over direct
evaluation of the DFT. The fast fourier transform algorithms exploit the two basic
/2
properties of the twiddle factor (symmetry property: w Nk + N = − w Nk ,

periodicity property: w Nk + N = w Nk ) and reduces the number of complex


2
multiplications required to perform DFT from N to N/2 log2N. In other words, for

N=1024, this implies about 5000 instead of 106 multiplications – a reduction factor of
200. FFT algorithms are based on the fundamental principal of decomposing the
computation of discrete fourier transform of a sequence of length N into successively
smaller discrete fourier transform of a sequence of length N into successively smaller
discrete fourier transforms. There are basically two classes of FFT algorithms. They
are decimation-in-time and decimation-in-frequency. In decimation-in-time, the
sequence for which we need the DFT is successively divided into smaller sequences
and the DFTs of these subsequences are combined in a certain pattern to obtain the
required DFT of the entire sequence. In the decimation-in-frequency approach, the
frequency samples of the DFT are decomposed into smaller and smaller
subsequences in a similar manner.

DIGITAL SIGNAL PROCESSING LAB 74


ELECTRONICS & COMMUNICATION ENGINEERING

Radix – 2 DIT – FFT algorithm

11. The number of input samples N=2M , where, M is an integer.


12. The input sequence is shuffled through bit-reversal.
13. The number of stages in the flow graph is given by M=log2 N.
14. Each stage consists of N/2 butterflies.

15. Inputs/outputs for each butterfly are separated by 2m-1 samples, where m
represents the stage index, i.e., for first stage m=1 and for second stage m=2
so on.
16. The no of complex multiplications is given by N/2 log2 N.
17. The no of complex additions is given by N log2 N.
18. The twiddle factor exponents are a function of the stage index m and is given
Nt
by k= m
t = 0,1,2,...2 m −1 − 1.
2
19. The no of sets or sections of butterflies in each stage is given by the formula
2M-m.
20. The exponent repeat factor (ERF), which is the number of times the exponent
sequence associated with m is repeated is given by 2M-m.
Radix – 2 DIF – FFT Algorithm

11. The number of input samples N=2M, where M is number of stages.


12. The input sequence is in natural order.
13. The number of stages in the flow graph is given by M=log2 N.
14. Each stage consists of N/2 butterflies.
15. Inputs/outputs for each butterfly are separated by 2M-m samples, Where m
represents the stage index i.e., for first stage m=1 and for second stage m=2
so on.
16. The number of complex multiplications is given by N/2 log2 N.
17. The number of complex additions is given by N log2 N.
18. The twiddle factor exponents are a function of the stage index m and is given
N
by k = t
M − m +1
, t = 0,1,2,...2 m − m − 1.
2
19. The number of sets or sections of butterflies in each stage is given by the
formula 2m-1.
20. The exponent repeat factor (ERF),Which is the number of times the exponent
sequence associated with m repeated is given by 2m-1.

DIGITAL SIGNAL PROCESSING LAB 75


ELECTRONICS & COMMUNICATION ENGINEERING

Program:
%To find the FFT of a given 1-D signal and plot
N=input ('enter the length of the sequence=');
M=input ('enter the length of the DFT=');
u=input ('enter the sequence u (n) =');
U=fft (u, M)
A=length (U)
t=0:1: N-1;
subplot (2, 2, 1);
stem (t, u);
title ('ORIGINAL TIME DOMAIN SEQUENCE');
xlabel ('---->n');
ylabel ('-->Amplitude');
subplot (2, 2, 2);
k=0:1:A-1;
stem (k, abs (U));
disp (‘abs (U) =');
disp (abs (U))
title ('MAGNITUDE OF DFT SAMPLES');
xlabel ('---->k');
ylabel ('-->Amplitude');
subplot (2, 1, 2);
stem (k, angle (U));
disp (‘angle (U) =')
disp (angle (U))
title ('PHASE OF DFT SAMPLES');
xlabel ('---->k');
ylabel ('-->phase');

DIGITAL SIGNAL PROCESSING LAB 76


ELECTRONICS & COMMUNICATION ENGINEERING

Output:
Enter the length of the sequence=3
Enter the length of the DFT=3
Enter the sequence u (n) = [1 2 3]
U = 6.0000 -1.5000 + 0.8660i -1.5000 - 0.8660i
A=3
abs (U) = 6.0000 1.7321 1.7321
angle (U) = 0 2.6180 -2.6180

Result: FFT of a given 1-D signal is determined and its magnitude and phase
plots are plotted.

DIGITAL SIGNAL PROCESSING LAB 77


ELECTRONICS & COMMUNICATION ENGINEERING

Inference: FFT reduces the computation time required to compute discrete


Fourier transform.

Questions & Answers


1. What is the FFT?

a. The Fast Fourier Transform (FFT) is simply a fast (computationally efficient) way to

calculate the Discrete Fourier Transform (DFT).

2. How does the FFT work?

a. By making use of periodicities in the sines that are multiplied to do the transforms,
the FFT greatly reduces the amount of calculation required. Functionally, the FFT
decomposes the set of data to be transformed into a series of smaller data sets to be
transformed. Then, it decomposes those smaller sets into even smaller sets. At each
stage of processing, the results of the previous stage are combined in special way.
Finally, it calculates the DFT of each small data set. For example, an FFT of size 32
is broken into 2 FFT's of size 16, which are broken into 4 FFT's of size 8, which are
broken into 8 FFT's of size 4, which are broken into 16 FFT's of size 2. Calculating a
DFT of size 2 is trivial. Here’s a slightly more rigorous explanation: It turns out that it
is possible to take the DFT of the first N/2 points and combine them in a special way
with the DFT of the second N/2 points to produce a single N-point DFT. Each of
these N/2-point DFTs can be calculated using smaller DFTs in the same way. One
(radix-2) FFT begins, therefore, by calculating N/2 2-point DFTs. These are
combined to form N/4 4-point DFTs. The next stage produces N/8 8-point DFTs, and
so on, until a single N-point DFT is produced.

3. How efficient is the FFT?

a. The DFT takes N^2 operations for N points. Since at any stage the computation
required to combine smaller DFTs into larger DFTs is proportional to N, and there are
log2 (N) stages (for radix 2), the total computation is proportional to N * log2 (N).
Therefore, the ratio between a DFT computation and an FFT computation for the
same N is proportional to N / log2 (n). In cases where N is small this ratio is not very
significant, but when N becomes large, this ratio gets very large. (Every time you
double N, the numerator doubles, but the denominator only increases by 1.)

DIGITAL SIGNAL PROCESSING LAB 78


ELECTRONICS & COMMUNICATION ENGINEERING

4. Are FFT's limited to sizes that are powers of 2?

a. No, The most common and familiar FFT's are "radix 2". However, other radices are
sometimes used, which are usually small numbers less than 10. For example, radix-4
is especially attractive because the "twiddle factors" are all 1, -1, j, or -j, which can be
applied without any multiplications at all. Also, "mixed radix" FFT's also can be done
on "composite" sizes. In this case, you break a non-prime size down into its prime
factors, and do an FFT whose stages use those factors. For example, an FFT of size
1000 might be done in six stages using radices of 2 and 5, since 1000 = 2 * 2 * 2 * 5
* 5 * 5. It might also be done in three stages using radix 10, since 1000 = 10 *10 *10.

DIGITAL SIGNAL PROCESSING LAB 79


ELECTRONICS & COMMUNICATION ENGINEERING

OTHER EXPERIMENTS

DIGITAL SIGNAL PROCESSING LAB 80


ELECTRONICS & COMMUNICATION ENGINEERING

1. GENERATION OF BASIC SEQUENCES


Aim: To generate impulse, step and sinusoidal sequences.

Program:
%Generation of basic sequences
%generation of impulse sequence
t=-2:1:2;
v= [zeros (1, 2), ones (1, 1), zeros (1, 2)]
subplot (2, 2, 1);
stem (t, v,'m','filled');
grid on;
ylabel ('---->Amplitude');
xlabel ('--->n');
title (' IMPULSE SEQUENCE');
%generation of step sequence
t=0:1:5;
m= [ones (1, 6)]
subplot (2, 2, 2);
stem (t, m,'m','filled');
grid on;
ylabel ('---->Amplitude');
xlabel ('--->n');
title (' STEP SEQUENCE');
%generation of sinusoidal sequence
t=-4:1:4;
y=sin (t)
subplot (2, 1, 2);
stem (t, y,'m','filled');
grid on;
ylabel ('---->Amplitude');
xlabel ('--->n');
title ('SINUSOIDAL SEQUENCE');

DIGITAL SIGNAL PROCESSING LAB 81


ELECTRONICS & COMMUNICATION ENGINEERING

Output:
v=0 0 1 0 0
m=1 1 1 1 1 1
y= 0.7568 -0.1411 -0.9093 -0.8415 0 0.8415 0.9093
0.1411
-0.7568

Result: Impulse, step and sinusoidal sequences are generated.

DIGITAL SIGNAL PROCESSING LAB 82


ELECTRONICS & COMMUNICATION ENGINEERING

2. DFT OF A SEQUENCE

Aim: To compute the DFT of a sequence.

Program:
%DFT of a sequence
N=input ('enter the length of the sequence=');
x=input ('enter the sequence=');
n= [0:1: N-1];
k= [0:1: N-1];
wN=exp (-j*2*pi/N);
nk=n'*k;
wNnk=wN. ^nk;
Xk=x*wNnk;
disp ('Xk=');
disp (Xk);
mag=abs (Xk)
subplot (2, 1, 1);
stem(k,mag);
grid on;
xlabel('--->k');
title ('MAGNITUDE OF FOURIER TRANSFORM');
ylabel ('Magnitude');
phase=angle (Xk)
subplot (2, 1, 2);
stem (k, phase);
grid on;
xlabel ('--->k');
title ('PHASE OF FOURIER TRANSFORM');
ylabel ('Phase');

DIGITAL SIGNAL PROCESSING LAB 83


ELECTRONICS & COMMUNICATION ENGINEERING

Output:

Enter the length of the sequence=5


Enter the sequence= [1 2 3 4 5]
Xk= 15.0000 -2.5000 + 3.4410i -2.5000 + 0.8123i -2.5000 –
0.8123i
-2.5000 - 3.4410i
mag = 15.0000 4.2533 2.6287 2.6287 4.2533
phase = 0 2.1991 2.8274 -2.8274 -2.1991

Result: DFT of a sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 84


ELECTRONICS & COMMUNICATION ENGINEERING

3. IDFT OF A SEQUENCE

Aim: To compute the IDFT of a sequence.

Program:
%IDFT of a sequence
Xk=input (‘enter X (K) =');
[N, M]=size (Xk);
if M~=1;
Xk=Xk.';
N=M;
end;
xn=zeros (N, 1);
k=0: N-1;
for n=0: N-1;
xn (n+1) =exp (j*2*pi*k*n/N)*Xk;
end;
xn=xn/N;
disp (‘x (n) = ');
disp (xn);
plot (xn);
grid on;
plot(xn);
stem(k,xn);
xlabel ('--->n');
ylabel ('-->magnitude');
title (‘IDFT OF A SEQUENCE’);

Output:
Enter the dft of X (K) = [6 -1.5+0.86i -1.5-0.86i]
x (n) =1.0000
2.0035 + 0.0000i
2.9965 - 0.0000i

DIGITAL SIGNAL PROCESSING LAB 85


ELECTRONICS & COMMUNICATION ENGINEERING

Result: IDFT of a given sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 86


ELECTRONICS & COMMUNICATION ENGINEERING

CODE COMPOSER STUDIO

DIGITAL SIGNAL PROCESSING LAB 87


ELECTRONICS & COMMUNICATION ENGINEERING

TEXAS INSTRUMENT DSP STARTER KIT 6711DSK


A BRIEF INTRODUCTION
1 Introduction

The purpose of this documentation is to give a very brief overview of the structure of
the 6711DSK. Included is also a mini tutorial on how to program the DSP, download
programs and debug it using the Code Composer Studio software.

2 The DSP starter kit

The Texas Instrument 6711DSK is a DSP starter kit for the TMS320C6711 DSP chip.
The kit contains:

• An emulator board which contains:


– DSP chip, memory and control circuitry.
– Input/output capabilities in the form of
_ An audio codec (ADC and DAC) which provides 1 input and 1 output
channel sampled at 8 kHz.
_ Digital inputs and outputs
_ A connector for adding external evaluation modules, like the PCM3003
Audio daughter card which has 2 analog in and 2 analog out sampled at
48 kHz.
– A parallel port for interface to a host computer used for program
development, program download and debugging.

• The Code Composer Studio (CCS) software which is an integrated development


environment (IDE) for editing programs, compiling, linking, download to target
(i.e., to the DSK board) and debugging. The CCS also includes the DSP/BIOS
real-time operating system. The DSP/BIOS code considerably simplifies the code
development for real-time applications which include interrupt driven and time
scheduled tasks.

DIGITAL SIGNAL PROCESSING LAB 88


ELECTRONICS & COMMUNICATION ENGINEERING

3 Usage overview

Working with the DSK involves the following steps:


• The first step is the algorithm development and programming in C/C++ or
assembler. We will only consider coding in C in this document. The program is typed
using the editor capabilities of the CCS. Also the DSP/BIOS configuration is
performed in a special configuration window.

• When the code is finished it is time to compile and link the different code parts
together. This is all done automatically in CCS after pressing the Build button. If
the compilation and linking succeeded the finished program is downloaded to the
DSK board.

• The operation of DSK board can be controlled using CCS, i.e., CCS also works as
a debugger. The program can be started and stopped and single-step. Variables in
the program can be inspected with the “Watch” functionality. Breakpoints can be
inserted in the code.

4 Getting started with the 6711DSK and CCS

In this section you will be introduced to the programming environment and will
download and execute a simple program on the DSK.

4.1 Connecting the PC and DSK

The DSK is communicating with the host PC using the parallel-port interface.

1. Start Code Composer Studio (CCS) by clicking on the “CCStudio 3.01” icon on the
workspace.

2. Check that the DSK is powered up. If not, power up the DSK by inserting the
AC power cable (mains) to the black AC/DC converter. Note: Never unplug the
power cable from the DSK card.

3. Make a connection between CCS and the DSK by selecting menu command
Debug! Connect. If connection fails perform following steps:

(a) Select menu command Debug! Reset Emulator

(b) Power cycle the DSK by removing the AC power cord from the AC/DC converter,
wait about a second and then reinsert.

(c) Select menu command Debug! Connect.

DIGITAL SIGNAL PROCESSING LAB 89


ELECTRONICS & COMMUNICATION ENGINEERING

4.2 Getting familiar with CCS

CCS arranges its operation around a project and the “Project view” window is
displayed to the left. Here you can find all files which are related to a certain project.
At the bottom of the CCS window is the status output view in which status information
will be displayed such as compile or link errors as well as other types of information.
Note that the window will have several tabs for different types of output.

4.3 Loading programs from CCS

One setting might need to be changed in CCS in order to automatically download the
program after compilation and linking (a build). You find the setting under menu
command Options! Customize and tab Program Load Options. Tick the box Load
Program after Build.

4.3.1 Project view and building an application

You open an existing project by right-clicking on the project folder and select the
desired “.pjt” file or select the command from the menu Project! Open....
• Open the project “intro.pjt” which you find in the “intro”folder.

• Press the “+” sign to expand the view. Several folders appear which contain all
the project specific files.

• Open up the Source folder. Here you will find all the files with source code which
belongs to the project.

• Double click on the “intro.c” file to open up an editor window with the file “intro.c” file
loaded.

• Look around in the file. The code calculates the inner product between two integer
vectors of length “COUNT” by calling the function “dotp” and then prints the result
using the “LOG printf” command.

• Compile, link and download the code selecting the Project! Build command or
use the associated button. If the download fails. Power cycle the DSK and retry
Project! Build.

DIGITAL SIGNAL PROCESSING LAB 90


ELECTRONICS & COMMUNICATION ENGINEERING

4.3.2 Running the code after a successful build command (compile, link and
download) the program is now resident in the DSK and ready for execution. A
disassembly window will appear showing the Assembly language instructions
produced by the compiler. You can minimize the window for now. At the bottom left
you will see the status “CPU HALTED” indicating that the CPU is not executing any
code. A few options are available depending on if you want to debug or just run the
code.

To simply run the code does:

• Select Debug! Run to start the execution. At the bottom left you will see the status
“CPU RUNNING” indicating that the program is executed.

• To stop the DSP select Debug! Halt.

• If you want the restart the program do Debug! Restart followed by Debug! Run
Try to run the code in the intro project. To see the output from the LOG printf
commands you must enable the view of the Message Log Window. Do DSP/BIOS!
Message Log and select LOG0 in the pull-down menu.

4.3.3 CCS Debug


Single stepping for debugging the code do the following:

• Select Debug! Go Main. This will run DSP/BIOS part of the code until the start
of the “main” function. A yellow arrow will appear to the left of the start of the
“main” function in the edit window for the “intro.c” file. The arrow indicates where
the program execution has halted.

• Now you can step the code one line at the time. Three commands are available:

– Debug! Step Into will execute the marked line if it is composed of simple
instructions or if the line has a function call, will step in to the called function.

– Debug! Step Over will execute the marked line and step to the next line.

DIGITAL SIGNAL PROCESSING LAB 91


ELECTRONICS & COMMUNICATION ENGINEERING

– Debug! Step Out will conclude the execution of the present function and halt
the execution at the next line of the calling function. Try to step through the code
using the step functions. View variables if you want to know the value of a particular
variable just put the cursor on top of the variable in the source window. The value will
after a short delay pop up next to the variable. Note that local variables in functions
only have defined values when the execution is located inside the function. Variables
can also be added to the “Watch window” which enables a concurrent view of several
variables. Mark the “y” variable in source code, right-click and select Add to Watch
Window. The watch window
will then add variable “y” to the view and show its contents. Also add the “a” variable
(which is a array) to the watch window. Since “a” is an array the value of “a” is an
address. Click on the “+”. This will show the individual values of the array. The watch
window will update its contents whenever the DSP is halted. It is also possible to
change the value of a variable in the DSK from the Watch window. Simply select the
numerical value you want to change and type in a new value. CCS will send the new
value to the DSK before starting the execution.
Break points Break points can also be used to halt the execution at a particular point
in the source code. To illustrate its use consider the “intro”. Place the cursor at the
line which has the “return (sum);” instruction in the “dotp” function. Right-click and
select Toggle breakpoint. A red dot will appear at that line indicating that a breakpoint
is set at that line. Try it out. First do Debug! Restart and then Debug! Run The
execution will halt at the line and we can investigate variables etc. To resume
execution simply issue Debug! Run command again. Shortcut buttons CCS offers a
number of shortcut buttons both for the build process as well as the debugging.
Browse around with the mouse pointer to find them. The balloon help function will
show what command a particular button is associated with, i.e., move the mouse
pointer over a button and wait for the balloon help to show up. Loading the values in
a vector into Matlab In the Lab you will need to load the coefficients of a FIR filter into
Matlab for further analysis. The filter coefficients are stored in vectors. Use the
following procedure:

1. Run the DSP program on the DSK.

2. Halt the execution when it is time to upload the vector.

3. In the File menu you find File! Data! Save In the file dialog assign a name to
the data file and select ”Float” as ”Save as type”.

DIGITAL SIGNAL PROCESSING LAB 92


ELECTRONICS & COMMUNICATION ENGINEERING

4. In the next dialog enter the name of the vector in the address field. When you tab
away from it it will change to the absolute memory address of the vector. In the
length box you enter the length of the variable. Note that you need to remove the 0x
prefix if you give the length using decimals numbers. The notation with 0x in the
beginning indicates that the number is a Hexadecimal number, i.e. it is based on a
base of 16 instead of the normal base of 10 in the decimal system.

5. Open the file in an editor and remove the first line and save again

6. In Matlab use the ”load” command to load the saved file. The vector will get the
same name as the file name without the extension.

5 Debugging - limitations
The debugging features of the CCS are very handy during the code development.
However, several limitations are present.

• Since the compiler will optimize the code, all lines in the C-code cannot be used as
breakpoints. Since the architecture has several parallel processing units the final
code might execute several lines of C in one clock cycle.

• The processor also has memory cache which speeds up normal operations. This
means that when the DSP loads a particular memory location it will copy it into
the cache memory and then perform the operations (faster) using the cache. After
some time the cache will be written back again to the memory. This can sometimes
confuse CCS and variables in the Watch window can be erroneous.

• The third important issue is when debugging code which is dependent on external
events, e.g., interrupt driven code. When halting such a code by a break point
several features are important to consider. Firstly, since the code is stopped all real-
time deadlines will be broken so future sampled inputs will be lost. Hence a restart
from the point of the break might cause unpredicted behavior.

• Sometimes the code in the DSK which communicates with the CCS stops working.
When this happens it is necessary to power cycle, the DSK board in order to restart
the operation. Sometimes it is also necessary at the same time to restart CCS.

DIGITAL SIGNAL PROCESSING LAB 93


ELECTRONICS & COMMUNICATION ENGINEERING

PROCEDURE TO WORK ON CODE COMPOSER


STUDIO

To create the new project


Project  new (File name.pjt, eg: vectors.pjt)

To create a source file


File newtype the code (save &give file name, eg: sum.c

To add source files to project


Project add files to projectsum.c

To add rts.lib file&hello.cmd:


Project  add files to project  rts6700.lib

Libraryfiles: rts6700.lib (path:c:\ti\c6000\cgtools\lib\rts6700.lib)


Note: select object&library in (*.o,*.1) in type of files

Project add files to projectshello.cmd

Cmd file – which is common for all non real time programs.
(path:c\ti\tutorials\dsk6711\hello.1\hello.cmd)

Note: select linker command file (*.cmd) in type of files

Compile:

To compile: projectcompile
To rebuild: projectrebuild

Which will create the final.outexecutablefile (eg.vectors.out)

Procedure to load and run program:

Load the program to DSK: file load programvectors. Out

To execute project: Debugrun

DIGITAL SIGNAL PROCESSING LAB 94


ELECTRONICS & COMMUNICATION ENGINEERING

C PROGRAMS
(USING64XX, 67XX SIMULATORS)

DIGITAL SIGNAL PROCESSING LAB 95


ELECTRONICS & COMMUNICATION ENGINEERING

1. TO VERIFY LINEAR CONVOLUTION


Aim: Write a C program for linear convolution of two discrete sequences and
compute using code composer studio V2 (using simulators 64xx, 67xx, 6711)
software.

Program:
#include<stdio.h>
#include<math.h>
main ()
{
int x[20],h[20],y[20],N1,N2,n,m;
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N1);
printf ("enter the length of the sequence h (n) :");
scanf ("%d", &N2);
printf ("enter the sequence x (n) :");
for (n=0; n<N1; n++)
scanf ("%d", &x[n]);
printf ("enter the sequence h (n) :");
for (n=0; n<N2; n++)
scanf ("%d", &h[n]);
for (n=0; n<N1+N2-1; n++)
{
if (n>N1-1)
{
y[n]=0;
for(m=n-(N1-1);m<=(N1-1);m++)
y[n] =y[n] +x[m]*h [n-m];
}
else
{
y[n] =0;
for (m=0; m<=n; m++)
y[n] =y[n] +x[m]*h [n-m];
}
}
printf ("convolution of two sequences is y (n) :");
for (n=0; n<N1+N2-1; n++)
printf ("%d\t", y[n]);
}

DIGITAL SIGNAL PROCESSING LAB 96


ELECTRONICS & COMMUNICATION ENGINEERING

Input:

Enter the length of the sequence x (n):4


Enter the length of the sequence h (n):3
Enter the sequence x (n):1 2 3 4
Enter the sequence h (n):5 6 7
Output:
Convolution of two sequences is y (n):5 16 34 52 45 28

Result: Linear convolution of two discrete sequences is computed.

DIGITAL SIGNAL PROCESSING LAB 97


ELECTRONICS & COMMUNICATION ENGINEERING

2. TO VERIFY CIRCULAR CONVOLUTION


Aim: Write a C program for circular convolution of two discrete sequences and
compute using code composer studio V2 (using simulators 64xx, 67xx, 6711)
software.

Program:

#include<math.h>
#define pi 3.14
main ()
{
int x[20],h[20],y[20],N1,N2,N,n,m,k;
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N1);
printf ("enter the length of the sequence h (n) :");
scanf ("%d", &N2);
printf ("enter the %d samples of sequence x (n):” N1);
for (n=0; n<N1; n++)
scanf ("%d", &x[n]);
printf ("enter the %d samples of sequence h (n):” N2);
for (n=0; n<N2; n++)
scanf ("%d", &h[n]);
if (N1>N2)
{
N=N1;
for (n=N2; n<N; n++)
h[n]=0;
}
else
{
N=N2;
for(n=N1;n<N1;n++)
y[n]=0;
}

DIGITAL SIGNAL PROCESSING LAB 98


ELECTRONICS & COMMUNICATION ENGINEERING

for(k=0;k<N;k++)
{
y[k]=0;
for (m=N-1; m>=0; m--)
{
if ((N+k-m)>=N)
{

y[k] =y[k] +x[m]*h [k-m];

}
else
y[k] =y[k] +x[m]*h [N+k-m];
}
}
printf ("\response is y (n) :");
for (n=0; n<N; n++)
printf ("\t%d", y[n]);
}

Input:

Enter the length of the sequence x (n):4

Enter the length of the sequence h (n):4

Enter the 4 samples of sequence x (n):2 1 2 1

Enter the 4 samples of sequence h (n):1 2 3 4

Output:

Response is y (n): 14 16 14 16

Result: Circular convolution of two discrete sequences is computed.

DIGITAL SIGNAL PROCESSING LAB 99


ELECTRONICS & COMMUNICATION ENGINEERING

3. DFT OF A SEQUENCE

Aim: Write a C program for DFT of a sequence and compute using code composer
studio V2 (using simulators 64xx, 67xx, 6711) software.

Program:

%DISCRETE FOURIER TRANSFORM OF THE GIVEN SEQUENCE


#include<stdio.h>
#include<math.h>
#define pi 3.14
main ()
{
int x [20], N, n, k;
float Xre[20],Xim[20],Msx[20],Psx[20];
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N);
printf ("enter the %d samples of discrete sequence x (n):” N);
for (n=0; n<N; n++)
scanf ("%d", &x[n]);
for(k=0;k<N;k++)
{
Xre[k]=0;
Xim[k]=0;
for(n=0;n<N;n++)
{
Xre[k]=Xre[k]+x[n]*cos(2*pi*n*k/N);
Xim[k]=Xim[k]+x[n]*sin(2*pi*n*k/N);
}
Msx[k]=sqrt(Xre[k]*Xre[k]+Xim[k]*Xim[k]);
Xim[k]=-Xim[k];
Psx[k]=atan(Xim[k]/Xre[k]);
}
printf ("discrete sequence is");

for (n=0; n<N; n++)

DIGITAL SIGNAL PROCESSING LAB 100


ELECTRONICS & COMMUNICATION ENGINEERING

printf ("\nx(%d) =%d", n,x[n]);


printf ("\nDFT sequence is :");
for(k=0;k<N;k++)
printf("\nx(%d)=%f+i%f",k,Xre[k],Xim[k]);
printf("\nmagnitude is:");
for (k=0; k<N; k++)
printf ("\n%f",Msx[k]);
printf ("\nphase spectrum is");
for(k=0;k<n;k++)
printf("\n%f",Psx[k]);
}
Input:
Enter the length of the sequence x (n):4
Enter the 4 samples of discrete sequence x (n):1 2 3 4
Output:
Discrete sequence is:
x (0) =1
x (1) =2
x (2) =3
x (3) =4

DFT sequence is :
x (0) =10.000000+i0.000000
x (1) =-2.007959+i1.995211
x (2) =-1.999967+i-0.012741
x (3) =-1.976076+i-2.014237

Magnitude is: Phase spectrum is:


0.000000 10.000000
-0.782214 2.830683
0.006371 2.000007
0.794961 2.821707

Result: DFT of a given sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 101


ELECTRONICS & COMMUNICATION ENGINEERING

4. IDFT OF A SEQUENCE

Aim: Write a C program for IDFT of a sequence and compute using code composer
studio V2 (using simulators 64xx, 67xx, 6711) software.

Program:
% Inverse Discrete Foureir Transform
#include<stdio.h>
#include<math.h>
#define pi 3.1428
main()
{
int j, k, N, n;
float XKr[10],XKi[10],xni[10],xnr[10],t;
printf (" enter seq length: \n");
scanf ("%d", &N);
printf ("enter the real & imaginary terms of the sequence: \n");
for (j=0; j<N; j++)
{
scanf ("%f%f", &XKr[j], &XKi[j]);
}
for (n=0; n<N; n++)
{
xnr[n] =0; xni[n] =0;
for(k=0;k<N;k++)
{
t=2*pi*k*n/N;
xnr[n]=( xnr[n]+XKr[k]*cos(t) - XKi[k]*sin(t)) ;
xni[n]=( xni[n]+XKr[k]*sin(t) + XKi[k]*cos(t)) ;
}
xnr[n]=xnr[n]/N;
xni[n]=xni[n]/N;
}
printf("IDFT seq:");

for(j=0;j<N;j++)

DIGITAL SIGNAL PROCESSING LAB 102


ELECTRONICS & COMMUNICATION ENGINEERING

{
printf("%f + (%f) i\n",xnr[j],xni[j]);
}
}

Input:

Enter seq length: 4

Enter the real & imaginary terms of the sequence:

3
0
0
-1
1
0
0
1

Output:

IDFT seq: 1.000000 + (0.000000) i


1.000000 + (0.000302) i
1.000603 + (0.000605) i
0.000006 + (-0.002717) i

Result: IDFT of a given sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 103


ELECTRONICS & COMMUNICATION ENGINEERING

5. N - POINT DISCRETE FOUREIR TRANSFORM

Aim: Write a C program for N - Point Discrete Foureir Transform of a sequence


and compute using code composer studio V2( using simulators 64xx,67xx,6711)
software.

Program:
% N - Point Discrete Foureir Transform
#include<stdio.h>
#include<math.h>
#define pi 3.142857
main ()
{
int j, k, n, N, l;
float XKr[10],XKi[10],xni[10],xnr[10],t;

printf (" enter seq length: \n");


scanf ("%d", &l);
printf ("enter the real & imaginary terms of the sequence: \n");
for (j=0; j<l; j++)
{
scanf ("%f%f", &xnr[j], &xni[j]);
}
printf (" enter required length: \n");
scanf ("%d", &N);
if (l<N)
{
for(j=l;j<N;j++)
xnr[j]=xni[j]=0;
}
for(k=0;k<N;k++)
{
XKr[k]=0; XKi[k]=0;
for(n=0;n<N;n++)
{
t=2*pi*k*n/N;

DIGITAL SIGNAL PROCESSING LAB 104


ELECTRONICS & COMMUNICATION ENGINEERING

XKr[k]=( XKr[k]+xnr[n]*cos(t) + xni[n]*sin(t)) ;

XKi[k]=( XKi[k]+ xni[n]*cos(t) - xnr[n]*sin(t)) ;


}
}

printf (" The %d Point DFT seq:” N);


for(j=0;j<N;j++)
{
printf("%3.3f + (%3.3f) i\n",XKr[j],XKi[j]);
}

Input:

Enter seq length:


3
Enter the real & imaginary terms of the sequence:
1
0
1
0
1
0
enter required length:
4

Out put:

The 4 Point DFT seq:3.000 + (0.000) i


-0.001 + (-0.999) i
1.000 + (-0.001) i
0.002 + (1.004) i

Result: 4 - Point Discrete Foureir Transform of a sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 105


ELECTRONICS & COMMUNICATION ENGINEERING

6. TO GENERATE SUM OF SINUSOIDAL SIGNALS

Aim: Write a C program to generate sum of sinusoidal signals and compute using
code composer studio V2 (using simulators 64xx, 67xx, 6711) software.

Program:

%SUM OF TWO SINUSOIDALS


#include<stdio.h>
#include<math.h>
main ()
{
int w1, w2, t;
float a, b, c;
printf ("enter the w1 value:");
scanf ("%d", &w1);
printf ("enter the w2 value:");
scanf ("%d", &w2);
printf ("sum of two sinusoidal :");
for(t=-5;t<5;t++)
{
b=sin(w1*t);
c=sin (w2*t);
a=b+c;
printf ("\n%f", a);
}
}

DIGITAL SIGNAL PROCESSING LAB 106


ELECTRONICS & COMMUNICATION ENGINEERING

Input:
Enter the w1 value: 5
Enter the w2 value: 5

Output:
Sum of two sinusoidal:
0.264704
-1.825891
-1.300576
1.088042
1.917849
0.000000
-1.917849
-1.088042
1.300576
1.825891

Result: samples of sum of sinusoidal signals are generated.

DIGITAL SIGNAL PROCESSING LAB 107


ELECTRONICS & COMMUNICATION ENGINEERING

PROGRAMS USING TMS 320C 6711 DSK

DIGITAL SIGNAL PROCESSING LAB 108


ELECTRONICS & COMMUNICATION ENGINEERING

1. TO VERIFY LINEAR CONVOLUTION


Aim: Write a C program for linear convolution of two discrete sequences and
compute using TMS 320C 6711 DSK.

Program:
#include<stdio.h>
#include<math.h>
main ()
{
int x[20],h[20],y[20],N1,N2,n,m;
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N1);
printf ("enter the length of the sequence h (n) :");
scanf ("%d", &N2);
printf ("enter the sequence x (n) :");
for (n=0; n<N1; n++)
scanf ("%d", &x[n]);
printf ("enter the sequence h (n) :");
for (n=0; n<N2; n++)
scanf ("%d", &h[n]);
for (n=0; n<N1+N2-1; n++)
{
if (n>N1-1)
{
y[n]=0;
for(m=n-(N1-1);m<=(N1-1);m++)
y[n] =y[n] +x[m]*h [n-m];
}
else
{
y[n] =0;
for (m=0; m<=n; m++)
y[n] =y[n] +x[m]*h [n-m];
}
}
printf ("convolution of two sequences is y (n) :");

DIGITAL SIGNAL PROCESSING LAB 109


ELECTRONICS & COMMUNICATION ENGINEERING

for (n=0; n<N1+N2-1; n++)


printf ("%d\t", y[n]);
}

Input:

Enter the length of the sequence x (n):4


Enter the length of the sequence h (n):3
Enter the sequence x (n):1 2 3 4
Enter the sequence h (n):5 6 7
Output:
Convolution of two sequences is y (n):5 16 34 52 45 28

Result: Linear convolution of two discrete sequences is computed.

DIGITAL SIGNAL PROCESSING LAB 110


ELECTRONICS & COMMUNICATION ENGINEERING

2. TO VERIFY CIRCULAR CONVOLUTION


Aim: Write a C program for circular convolution of two discrete sequences and
compute using using TMS 320C 6711 DSK.
Program:
#include<math.h>
#define pi 3.14
main ()
{
int x[20],h[20],y[20],N1,N2,N,n,m,k;
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N1);
printf ("enter the length of the sequence h (n) :");
scanf ("%d", &N2);
printf ("enter the %d samples of sequence x (n):", N1);
for (n=0; n<N1; n++)
scanf ("%d", &x[n]);
printf ("enter the %d samples of sequence h (n):” N2);
for (n=0; n<N2; n++)
scanf ("%d", &h[n]);
if (N1>N2)
{
N=N1;
for (n=N2; n<N; n++)
h[n]=0;
}
else
{
N=N2;
for(n=N1;n<N1;n++)
y[n]=0;
}

DIGITAL SIGNAL PROCESSING LAB 111


ELECTRONICS & COMMUNICATION ENGINEERING

for(k=0;k<N;k++)
{
y[k]=0;
for (m=N-1; m>=0; m--)
{
if ((N+k-m)>=N)
{

y[k] =y[k] +x[m]*h [k-m];

}
else
y[k] =y[k] +x[m]*h [N+k-m];
}
}
printf ("\response is y (n) :");
for (n=0; n<N; n++)
printf ("\t%d", y[n]);
}

Input:

Enter the length of the sequence x (n):4

Enter the length of the sequence h (n):4

Enter the 4 samples of sequence x (n):2 1 2 1

Enter the 4 samples of sequence h (n):1 2 3 4

Output:
Response is y (n): 14 16 14 16

Result: Circular convolution of two discrete sequences is computed.

DIGITAL SIGNAL PROCESSING LAB 112


ELECTRONICS & COMMUNICATION ENGINEERING

3. FINDING DFT OF A SEQUENCE

Aim: Write a C program for DFT of a sequence and compute using TMS 320C
6711 DSK.

Program:

%DISCRETE FOURIER TRANSFORM OF THE GIVEN SEQUENCE


#include<stdio.h>
#include<math.h>
#define pi 3.14
main ()
{
int x [20], N, n, k;
float Xre[20],Xim[20],Msx[20],Psx[20];
printf ("enter the length of the sequence x (n) :");
scanf ("%d", &N);
printf ("enter the %d samples of discrete sequence x (n):” N);
for (n=0; n<N; n++)
scanf ("%d", &x[n]);
for(k=0;k<N;k++)
{
Xre[k]=0;
Xim[k]=0;
for(n=0;n<N;n++)
{
Xre[k]=Xre[k]+x[n]*cos(2*pi*n*k/N);
Xim[k]=Xim[k]+x[n]*sin(2*pi*n*k/N);
}
Msx[k]=sqrt(Xre[k]*Xre[k]+Xim[k]*Xim[k]);
Xim[k]=-Xim[k];
Psx[k]=atan(Xim[k]/Xre[k]);
}
printf ("discrete sequence is:");

for (n=0; n<N; n++)

DIGITAL SIGNAL PROCESSING LAB 113


ELECTRONICS & COMMUNICATION ENGINEERING

printf ("\nx (%d) =%d", n, x[n]);


printf ("\nDFT sequence is :");
for(k=0;k<N;k++)
printf("\nx(%d)=%f+i%f",k,Xre[k],Xim[k]);
printf ("\nmagnitude is:");
for (k=0; k<N; k++)
printf ("\n%f", Msx[k]);
printf ("\nphase spectrum is:");
for(k=0;k<n;k++)
printf("\n%f",Psx[k]);
}
Input:
Enter the length of the sequence x (n):4
Enter the 4 samples of discrete sequence x (n):1 2 3 4
Output:
Discrete sequence is:
x (0) =1
x (1) =2
x (2) =3
x (3) =4

DFT sequence is :
x (0) =10.000000+i0.000000
x (1) =-2.007959+i1.995211
x (2) =-1.999967+i-0.012741
x (3) =-1.976076+i-2.014237

Magnitude is: Phase spectrum is:


0.000000 10.000000
-0.782214 2.830683
0.006371 2.000007
0.794961 2.821707

Result: DFT of a given sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 114


ELECTRONICS & COMMUNICATION ENGINEERING

4. FINDING IDFT OF A SEQUENCE

Aim: Write a C program for IDFT of a sequence and compute using TMS 320C
6711 DSK.

Program:
% Inverse Discrete Foureir Transform
#include<stdio.h>
#include<math.h>
#define pi 3.1428
main ()
{
int j, k, N, n;
float XKr[10],XKi[10],xni[10],xnr[10],t;
printf (" enter seq length: \n");
scanf ("%d", &N);
printf ("enter the real & imaginary terms of the sequence: \n");
for (j=0; j<N; j++)
{
scanf ("%f%f", &XKr[j], &XKi[j]);
}
for (n=0; n<N; n++)
{
xnr[n] =0; xni[n] =0;
for(k=0;k<N;k++)
{
t=2*pi*k*n/N;
xnr[n]=( xnr[n]+XKr[k]*cos(t) - XKi[k]*sin(t)) ;
xni[n]=( xni[n]+XKr[k]*sin(t) + XKi[k]*cos(t)) ;
}
xnr[n]=xnr[n]/N;
xni[n]=xni[n]/N;
}
printf("IDFT seq:");
for(j=0;j<N;j++)
{
printf("%f + (%f) i\n",xnr[j],xni[j]);
}
}

DIGITAL SIGNAL PROCESSING LAB 115


ELECTRONICS & COMMUNICATION ENGINEERING

Input:

Enter seq length:


4

Enter the real & imaginary terms of the sequence:

3
0
0
-1
1
0
0
1
Output:

IDFT seq: 1.000000 + (0.000000) i


1.000000 + (0.000302) i
1.000603 + (0.000605) i
0.000006 + (-0.002717) i

Result: IDFT of a given sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 116


ELECTRONICS & COMMUNICATION ENGINEERING

5. N - POINT DISCRETE FOUREIR TRANSFORM

Aim: Write a C program for N - Point Discrete Foureir Transform of a sequence and
compute using TMS 320C 6711 DSK.

Program:
% N - Point Discrete Foureir Transform
#include<stdio.h>
#include<math.h>
#define pi 3.142857
main ()
{
int j, k, n, N, l;
float XKr[10],XKi[10],xni[10],xnr[10],t;

printf (" enter seq length: \n");


scanf ("%d", &l);
printf ("enter the real & imaginary terms of the sequence: \n");
for (j=0; j<l; j++)
{
scanf ("%f%f", &xnr[j], &xni[j]);
}
Printf (" enter required length: \n");
Scanf ("%d", &N);
if (l<N)
{
for(j=l;j<N;j++)
xnr[j]=xni[j]=0;
}
for(k=0;k<N;k++)
{
XKr[k]=0; XKi[k]=0;
for(n=0;n<N;n++)
{
[

DIGITAL SIGNAL PROCESSING LAB 117


ELECTRONICS & COMMUNICATION ENGINEERING

t=2*pi*k*n/N;

XKr[k]=( XKr[k]+xnr[n]*cos(t) + xni[n]*sin(t)) ;


XKi[k]=( XKi[k]+ xni[n]*cos(t) - xnr[n]*sin(t)) ;
}

Printf (" The %d Point DFT seq:” N);


for(j=0;j<N;j++)
{
printf("%3.3f + (%3.3f) i\n",XKr[j],XKi[j]);
}

Input:

Enter seq length:


3
Enter the real & imaginary terms of the sequence:
1
0
1
0
1
0
Enter required length:
4

Out put:

The 4 Point DFT seq: 3.000 + (0.000) i


-0.001 + (-0.999) i
1.000 + (-0.001) i
0.002 + (1.004) i
Result: 4 - Point Discrete Foureir Transform of a sequence is computed.

DIGITAL SIGNAL PROCESSING LAB 118


ELECTRONICS & COMMUNICATION ENGINEERING

6. TO GENERATE SUM OF SINUSOIDAL SIGNALS

Aim: Write a C program to generate sum of sinusoidal signals and compute using
TMS 320C 6711 DSK.

Program:
%SUM OF TWO SINUSOIDALS
#include<stdio.h>
#include<math.h>
main ()
{
int w1, w2, t;
float a, b, c;
printf ("enter the w1 value :");
scanf ("%d", &w1);
printf ("enter the w2 value :");
scanf ("%d", &w2);
printf ("sum of two sinusoidal :");
for(t=-5;t<5;t++)
{
b=sin(w1*t);
c=sin (w2*t);
a=b+c;
printf ("\n%f", a);
}
}

DIGITAL SIGNAL PROCESSING LAB 119


ELECTRONICS & COMMUNICATION ENGINEERING

Input:

Enter the w1 value: 5


Enter the w2 value: 5
Output:
Sum of two sinusoidal:
0.264704
-1.825891
-1.300576
1.088042
1.917849
0.000000
-1.917849
-1.088042
1.300576
1.825891

Result: Samples of sum of sinusoidal signals are obtained.

DIGITAL SIGNAL PROCESSING LAB 120


ELECTRONICS & COMMUNICATION ENGINEERING

REFERENCES
1. Rabiner, Lawrence R. & Gold, Bernard, Theory and application of digital
signal processing, Prentice-Hall (1975).
2. Proakis, J.G. and Manolakis, D.G., Digital signal processing: principles,
algorithms and applications, Macmillan (1996).
3. A. V. Oppenheim and R. W. Schafer, Digital Signal Processing, Prentice-Hall,
(1975).
4. Sanjit K.Mitra, Digital Signal Processing, A Computer based approach, Tata
McGraw-Hill, (1998).
5. Vinay K. Ingle and John G. Proakis, Digital Signal Processing using
MATLAB, BookWare Companion Series,(2001).
6. Rudra Pratap, Getting Started With MATLAB: A Quick Introduction for
Scientists and Engineers, Oxford University Press.
7. Avtar Singh and S.Srinivasan, Digital Signal Processing Implementations,
Penram International Publishing (India) Pvt. Ltd.

121

Das könnte Ihnen auch gefallen