Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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 lineediting. Finally, as you might well expect, backspace will delete the character to the left of the cursor.
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. 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] Similarly, the permanent variable NaN represents a value which is not a number, such as the result
results in x= 2 1 4 3 6 5 8 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).
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 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. 7 6 5
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.
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-byfour 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)).
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
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 fourquadrant 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 Columns 5 through 8 -1.0000 + 0.0000i 0.7071 -0.7071 i -0.7071 i - 0.7071 i 0.0000 - 1.0000i 0.0000 + 1.0000i -0.7071 + 0.7071 i
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.
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 xaxis') 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.
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.
10
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 (~=), lessthan 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.
11
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 UNIXs 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.
12
If we define a and b to represent a system described by the difference equation: y(n) =: )( i ) *x(n) - 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. all of a by a (1). 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 + b(2) Din- 1 ) + ...+ b(nb)*x(n-nb+l)
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 twoelement 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 ztransform, 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.
13
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.
14
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 2.0000 + 1.0000i 3.0000 + 1.0000i 1.0000 + 2.0000i 2.0000 + 9.0000i 3.0000 + 2.0000i 1.0000 + 3.0000i 2.0000 + 3.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
15
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.
16
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,
17
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.
18
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 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. 3 5
19
20
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
21
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
22
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 MATLabs 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))
Operators
Expressions use familiar arithmetic operators and precedence rules. + Addition - Subtraction * Multiplication / Division
23
\ 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
24
25
26
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.
27
28
29
30
RSQRDP RSQRSP
31
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, 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;
32
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:
33
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 =
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)].
34
N 1
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
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.
35
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');
36
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 1 0 0 1 0 1 1 0 0 0 0 1 1 0 1 0 0 1
z= 7 5 7 9
37
x (m) x
1
m =0
((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) =
x
n =0
N 1
(n)e j 2kn / N
38
Hd (e ) = Where
jw
h (n)e
d n=
jwn
Hd(n) =
1/ 2 H (e j )e jn 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
H(ejw) = 1/ 2
(e
)W ( e
j ( )
Hd(ejw) * W (ejw) Because both Hd (ejw) and W (ejw) are periodic function, the operation often called as periodic convolution.
39
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.0000 0.0000 Columns 18 through 25 -0.0654 -0.0000 0.0467 -0.0000 -0.0363 -0.0000 0.0297 -0.0000 0.0297 -0.0000 -0.0363 -0.0000 0.1090 -0.0000 -0.3269 0.0467 -0.0000 -0.0654 0.1090 0.5135 -0.3269 -0.0000
40
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.
41
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 dont 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.
42
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,
43
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 delayline 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.
I0(x) = 1+
[1 / k! (x/2) ]
k =1
k 2
44
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.0641 -0.0186 -0.0206 0.0229 0.1501 0.0258 0.4507 -0.0294 0.4507 -0.0341 0.0405 0.0497 -0.0641 -0.0899 0.1501 -0.0899 -
45
Columns 18 through 26 0.0497 0.0170 b = Columns 1 through 17 0.0024 0.0573 Columns 18 through 26 0.0412 0.0024 b = Columns 1 through 17 0.0000 0.0467 Columns 18 through 26 0.0293 0.0000 0.0182 -0.0109 -0.0062 0.0032 0.0015 -0.0006 -0.0002 -0.0002 -0.0006 0.0015 0.1416 0.0032 0.4473 -0.0062 0.4473 -0.0109 0.0182 0.0293 - 0.0467 -0.0766 0.1416 -0.0766 0.0305 -0.0227 -0.0169 0.0124 0.0089 -0.0062 -0.0041 -0.0041 -0.0062 0.0089 0.1471 0.0124 0.4496 -0.0169 0.4496 -0.0227 0.0305 0.0412 -0.0573 -0.0849 0.1471 -0.0849 0.0405 -0.0341 -0.0294 0.0258 0.0229 -0.0206 -0.0186
46
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.
47
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.
Ha (s) =
K =1
ck / s p k
48
H (z) =
K =1 N
ck /1 e
pkT
z 1
Tc
/1 e
pkT
z 1
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);
49
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 0.0018 a = 1.0000 -0.1024 0.7816 -0.0484 0.1152 -0.0032
50
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.
51
b)
52
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 a = 1.0000 -1.6168 1.4278 -0.4759 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.
53
54
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 properties of the twiddle factor (symmetry property: periodicity property:
k k w N+ N = w N
k w N+ N
/2
k = wN
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.
55
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 by
k=
Nt t = 0,1,2,...2 m 1 1. m 2
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 by k =
t M m +1
, t = 0,1,2,...2 m m 1.
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.
56
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)
57
Output:
enter N value=5 type input sequence= [1 1 0] L= 3 x1 = 1 angle= 0 1 0 0 0 1.6180 0.6180 0.6180 1.6180 1.2566 -1.2566 -0.6283 abs (Xk) = 2.0000 0.6283
58
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 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, radix. In the
59
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/secondhalf approach, which is called a "Decimation-In-Frequency" (DIF) FFT. Generally, the user does not need to worry which type is being used.
60
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 MATLabs 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;
61
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.4794 0 0.4794 0.8415 0.9975 0.2794 0.9093 0.9589 0.5985 0.1411 -0.3508 0.7568 y2 = -0.9894 -0.6570 0.8415 0 0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794 0.1383 1.1386 0.6570 0.9894 y3 =-0.2326 -0.3062 1.3209 0 1.3209 1.7508 0.1525 -0.3605 -0.1383 0.3062 0.2326 0.3605 -0.1525 -1.1386 -1.7508 0.7568 -0.1411 -0.9093 0.3508 -0.1411 -0.5985 -0.9093 -0.9975 -0.8415 -
62
Result:
Sum of sinusoidal signals is generated. The lengths of x1 (n) and x2 (n) must be the same for sample-bysample addition.
Inference:
63
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.
log N =
10 10 log
0 . 1 0 . 1
1 1
S P
Two properties of Butterworth lowpass filter 1. The magnitude response of the butterworth filter decreases
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 4.
c=
5. Find the transfer function Ha (s) for the above value of H(s).
by substituting
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;
64
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.2644 0.1653 -0.1362 0.0412 -0.0080 0.0013 -0.0001 0.0000 0.0735 0.0220 0.0040 0.0003 1.5475 -0.7945 0.4106 a = 1.0000 -1.1997 2.2442 -1.7386 0.0040 0.0220 0.0735 0.1653 0.2644 0.3085
65
Result: Butterworth analog low pass filter is designed and its frequency response
is found.
The magnitude response of the Butterworth filter closely approximates the ideal response as the order N increases.
66
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 allpole 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] 2
Where
= -1 + =
-2 + 1
100.1 p - 1 frequency
p = passband
67
1 rad/sec)
4. Calculate the poles of Chebyshev filter which lies on an ellipse by using the formula. Sk = a cosk + 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 + And = 1+ -2
(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);
68
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 a = 1.0000 -1.6168 1.4278 -0.4759 1.0366 -0.1540
69
Result:
Chebyshew type I analog high pass filter is designed and its frequency response is observed.
70
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)
71
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
72
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.
73
Substituting W N = e j 2 / N , we have
nk X (k ) = x (n)W N 0 k N - 1 n =0 N 1
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 properties of the twiddle factor (symmetry property: periodicity property:
k k w N+ N = w N k w N+ N /2 k = wN
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.
74
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 by
k=
Nt t = 0,1,2,...2 m 1 1. m 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 by k =
t M m +1
, t = 0,1,2,...2 m m 1.
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.
75
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');
76
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 A=3 abs (U) = 6.0000 angle (U) = 0 1.7321 1.7321 2.6180 -2.6180 -1.5000 + 0.8660i -1.5000 - 0.8660i
Result: FFT of a given 1-D signal is determined and its magnitude and phase
plots are plotted.
77
78
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.
79
OTHER EXPERIMENTS
80
81
Output:
v=0 m=1 0.1411 -0.7568 0 1 1 1 0 1 0 1 1 0.8415 0.9093
82
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');
83
Output:
Enter the length of the sequence=5 Enter the sequence= [1 2 3 4 5] Xk= 15.0000 -2.5000 + 3.4410i 0.8123i -2.5000 - 3.4410i mag = 15.0000 phase = 0 4.2533 2.6287 2.6287 4.2533 2.1991 2.8274 -2.8274 -2.1991 -2.5000 + 0.8123i -2.5000
84
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
85
Result:
86
87
88
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.
89
90
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.
91
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.
92
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 realtime 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.
93
Project
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: project To rebuild: project
compile rebuild
Which will create the final.outexecutablefile (eg.vectors.out) Procedure to load and run program: Load the program to DSK: file To execute project: Debug
run load program vectors. Out
94
95
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]); }
96
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:
97
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; }
98
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
99
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");
100
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: 0.000000 -0.782214 0.006371 0.794961 Phase spectrum is: 10.000000 2.830683 2.000007 2.821707
Result:
101
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++)
102
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:
103
and compute using code composer studio V2( using simulators 64xx,67xx,6711)
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;
104
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
105
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); } }
106
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
107
108
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) :");
109
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:
110
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; }
111
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
112
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:");
113
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: 0.000000 -0.782214 0.006371 0.794961 Phase spectrum is: 10.000000 2.830683 2.000007 2.821707
Result:
114
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]); } }
115
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:
116
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++) {
[
117
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
118
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); } }
119
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
120
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. 6. Vinay K. Ingle and John G. Proakis, Digital Signal Processing using MATLAB, BookWare Companion Series,(2001). 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