Feb 21, 2013 - The âMATLABâ name is obtained by combining the initials .... Solution: Paste printed cutting of your results for above mentioned task in space ...
2013 Sr. No. Date 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Signals and Systems
Experiment Introduction to Matlab Intro. to Loops and M files in Matlab Signals (Unit Step and Impulse) & Graphs Exponential and Sinusoidals Implementing Convolution Sum Introduction to Matlab toolbox Implementation of Convolution Integral Fourier Analysis sis and Synthesis Continuous ntinuous Time Fourier Transform Implementation in Matlab Discrete iscrete Time Fourier Transform Implementation in Matlab Application in Signal Processing (filters and audio signals) Application in Image Processing Laplace Transforms Laplace Transforms
Marks
Lab Manual
Rabya Bahadur Khan Hoti Gul Zameen Khan COMSATS IIT 2/21/2013
COMSATS IIT 2 Signals and Systems Sr. No. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.
Title “Introduction to MATLAB” “Introduction to Loops and M files in Matlab” “Signals (Unit Step and Impulse) & Graphs” “Exponential and Sinusoidals” “Implementing Convolution Sum” “Introduction to Matlab toolbox” “Implementation of convolution integral” “Implementation of Fourier Analysis and Fourier Synthesis” Lab 09 “Continuous Time Fourier Transform Implementation in Matlab” “Discrete Time Fourier Transform Implementation in Matlab” Matlab Applications in system analsys Matlab Applications in adance systems (Image processing / Communication) Project Project Project Project
Electrical Engineering Department
Page No.
Teacher’s Option
Page 2
COMSATS IIT 3 Signals and Systems Lab 1: “Introduction to MATLAB” The topics that will be covered today are Control structures(Logical, relational, branching and looping constructs). The “MATLAB” name is obtained by combining the initials corresponding to MATrix LABoratory. For detailed information regarding Matlab refer to www.mathworks.com. Windows: There are several window types. The desktop includes the main windows corresponding to the MATLAB core. However, in a typical session a number of secondary windows are opened and closed in order to show figures, user interfaces, variable and file editors, SIMULINK models and libraries… Also, specific windows exist for both the help and demos.
Getting to know different windows: o o
Workspace. Command Window
Work space shows all variables in use All executions are done in the command window. All commands are written here and different variables are formed
Electrical Engineering Department
Page 3
COMSATS IIT 4 Signals and Systems o
Command History
It gives you an incite about the previously used commands with date and time
o
Current Directory and directory path
Here we choose the folder where we want our Matlab files to stored and access from In current directory we can easily view all the folders and Matlab files that we need to access and all other related files in that particular directory
Getting familiar with basic instructions: o Help provides help on any Matlab command about which you want to learn o clc it clears the command window o clear it clears all the workspace/ deletes all variables in use o save saves all data/ variables present in workspace o load load any Matlab file that was previously saved o close all closes all figures that are currently open o figure opens a new figure o close closes recently opened figure o plot (x,y)plots x along x-axis and y along y-axis.
Electrical Engineering Department
Page 4
COMSATS IIT 5 Signals and Systems
Variables: Constitute the temporary objects (when the user exits MATLAB, all variables are deleted) and they are stored in the so-called workspace.
Working with scalars Variables are assigned numerical values by typing the expression directly in command window (for beginners), for example, typing a = 1+2 yields: a = 3 The answer will not be displayed when a semicolon is put at the end of an expression. However, the variable will be assigned value and can be viewed in workspace, for example type a = 1+2;. MATLAB utilizes the following arithmetic operators: + addition - subtraction * multiplication / division ^ power operator ' transpose Example: b = 2*a; To determine the value of a previously defined quantity, type the quantity by itself: b yields: b = 6 If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the line) and continue on the next line. c = 1+2+3+... 5+6+7;
sqrt(-1) i sqrt(-1) j 3.1416... pi Example: y= 2*(1+4*j) yields: y = 2.0000 + 8.0000i In order to view complex number use compass command, for more details use help command. Working with matrices: MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vector and matrix operations are as simple as common calculator operations.Vectors can be defined in two ways. o The first method is used for arbitrary elements: Example: v = [1 3 5 7]; creates a 1x4 vector with elements 1, 3, 5 and 7. Note that commas could have been used in place of spaces to separate the elements. Additional elements can be added to the vector: v(5) = 8; yields the vector v = [1 3 5 7 8]. Previously defined vectors can be used to define a new vector. Example( with v defined above) Electrical Engineering Department
Page 5
COMSATS IIT 6 Signals and Systems
o
a = [9 10]; b = [v a]; creates the vector b = [1 3 5 7 8 9 10]. The second method is used for creating vectors with equally spaced elements: t = 0:0.1:10; creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number defines the increment. If only two numbers are given, then the increment is set to a default of 1: k = 0:10; creates a 1x11 vector with the elements 0, 1, 2, ..., 10. Matrices are defined by entering the elements row by row: M = [1 2 4; 3 6 8]; 124 creates the matrix ? = ? ? 368 There are a number of special matrices that can be defined: null matrix: M = [ ]; n x m matrix of zeros: M = zeros(n,m); n x m matrix of ones: M = ones(n,m); n x n identity matrix: M = eye(n); A particular element of a matrix can be assigned: M(1,2) = 5; places the number 5 in the first row, second column. Operations and functions that were defined for scalars in the previous section can also be used on vectors and matrices. Example: a = [1 2 3]; b = [4 5 6]; c=a+b yields: 9 c= 5 7 Functions are applied element by element. Example: t = 0:10; x = cos(2*t); creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10. Operations that need to be performed element-by-element can be accomplished by preceding the operation by a ".". For example, to obtain a vector x that contains the elements of x(t) = tcos(t) at specific points in time, you cannot simply multiply the vector t with the vector cos(t). Instead you multiply their elements together:
t = 0:10; x = t.*cos(t); Task: Explore compass, legends and hold commands using help and plot any five complex numbers on one compass figure. Each complex number should be represented with a different color and legends should express the name of every complex number.
Electrical Engineering Department
Page 6
COMSATS IIT 7 Signals and Systems
Solution: Paste printed cutting of your results for above mentioned task in space provided below:
Plot the given Complex number on compass diagram given at right hand side
90 8 120
60 6
150
1. 2. 3. 4.
30
4
2
180
??
?? ? ? − ?? 0.9+j3 ? < −120
0
210
330
240
300 270
Hand work Electrical Engineering Department
Page 7
COMSATS IIT 8 Signals and Systems Lab 2: “Introduction to Loops and M files in Matlab” The topics that will be covered today are Control structures(Logical, relational, branching and looping constructs). 2.1 M-Files While working in command window we normally face two very excruciating issues: 1. In case of any error we need to retype all our code again. 2. Even if you do not make any mistakes, all of your work may be lost if you inadvertently quit MATLAB. In order to overcome above mentioned issues and to preserve large sets of commands, you can store them in a special type of file called an M-file. MATLAB supports two types of M-files: 1. Script 2. Function. 1) Scripts: To hold a large collection of commands, we use a script M-file. The script file has a '.m' extension and is referred to as an M-file (for example, myfile.m myfuncion.m, etc.). The commands in the script file can then be executed by typing the file name without its extension in the command window or by clicking ‘Run’ icon or simply by pressing F5 button while ‘M-file’ is open. Commands in a script utilize and modify the contents of the current workspace. It is possible to embed comments in a script file. To make a script M-file, you need to open a file using the built-in MATLAB editor. There are two ways to accomplish it: 1. From file menu, click NEW
2. Type edit on command line Electrical Engineering Department
Page 8
COMSATS IIT 9 Signals and Systems A new window appears like one shown in the figure below.
When you are finished with typing in this new window, click File->Save to save this file. The extension of this file be .m. In order to execute this program, 1. Write the name of file on command window (excluding the .m) or 2. Click Debug->Run Example: Let’s make a script to execute the commands >>x=10; >>y=20; >>z=x+y First of all go to File->New->Script An editor will be opened. Then write the above command in the editor as shown below:
Electrical Engineering Department
Page 9
COMSATS IIT 10 Signals and Systems
Now save it, let’s say with the name script1.m. Close the editor and go back to command window and write the script name as: >>script1 Z= 30 You could also run the script from the editor window Debug- Run or By pressing F5
2)
FUNCTIONS
A function is a reusable portion of code that can be called from program to accomplish some specified functionality. A function takes some input arguments and returns some output. What do I have to put on the First Line of a MATLAB function? The 1st line of a function must contain the “function definition,” which has a general structure like this: function [Out_1,Out_2,…,Out_N] = function_name(In_1,In_2,…,In_M) where Out_1,Out_2,…,Out_N are the N output variables and In_1,In_2,…,In_M are the M input variables; If there is only a single output variable use: function Out_1 = function_name(In_1,In_2,…,In_M) If there is no output variable use: function function_name(In_1,In_2,…,In_M)
Electrical Engineering Department
Page 10
COMSATS IIT 11 Signals and Systems What do I have to put after the 1st line? After the first line, you just put a sequence of MATLAB commands – with one command per line – just like you are computing in MATLAB, in the command line environment. This sequence of commands is what makes up your program – you perform computations using the input variables and other variables you create within the function and in doing so, you create the output variables you desire. How to create a function: To create a function that adds two numbers and strores the result in a third variable, type in it the following code: function add x=3; y=5; z=x+y Save the file by the name of add (in work folder, which is chosen by default), go back to the command window and write » add z= 8 You see that the sum z is displayed in the command window. Now go back to the editor/debugger and modify the program as follows function addv(x,y) z=x+y Save the above program with a new name addv, go back to the command window and type the following » addv(3,5) z= 8 » addv(5,5) z= 10 We have actually created a function of our own and called it in the main program and gave values to the variables (x,y). Now go back to the editor/debugger and modify the program as follows function adv(x,y) %------------------------------------------------% This function takes two values as input, % finds its sum, & displays the result. % inputs: x & y % output: z % Example: addv(3,6) % Result: z=9 %-------------------------------------------------z=x+y Save the program with the same name addv, go back to command window, type the following » help addv ------------------------------------------------This function takes two values as input, Electrical Engineering Department
Page 11
COMSATS IIT 12 Signals and Systems finds its sum, & displays the result. inputs: x & y output: z Example: addv(3,6) Result: z=9 -------------------------------------------------SCRIPT VS FUNCTION
A script is simply a collection of Matlab commands in an m-file. Upon typing the name of the file (without the extension), those commands are executed as if they had been entered at the keyboard. Functions are used to create user-defined matlab commands.
A script can have any name. A function file is stored with the name specified after keyword function.
The commands in the script can refer to the variables already defined in Matlab, which are said to be in the global workspace. When a function is invoked, Matlab creates a local workspace. The commands in the function cannot refer to variables from the global (interactive) workspace unless they are passed as inputs. By the same token, variables created as the function executes are erased when the execution of the function ends, unless they are passed back as outputs.
2.2 CONTROL STRUCTURES Control-of-flow in MATLAB programs is achieved with logical/relational constructs, branching constructs, and a variety of looping constructs. Relational and logical constructs The relational operators in MATLAB are Operator Description =================================== < less than > greater than = greater than or equal == equal ~= not equal. =================================== Note that ``='' is used in an assignment statement while ``=='' is used in a relation. Relations may be connected or quantified by the logical operators Operator Description =================================== & and | or ~ not. Electrical Engineering Department
Page 12
COMSATS IIT 13 Signals and Systems =================================== When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or false (indeed, throughout this section you should think of 1 as true and 0 as false). For example >> 3 < 5 ans = 1 >> a = 3 == 5 a= 0 When logical operands are applied to matrices of the same size, a relation is a matrix of 0's and 1's giving the value of the relation between corresponding entries. For example: >> A = [ 1 2; 3 4 ]; >> B = [ 6 7; 8 9 ]; >> A == B ans = 0 0 0 0 >> A < B ans = 1 1 1 1 To see how the other logical operators work, you should also try >> ~A >> A&B >> A & ~B >> A | B >> A | ~A Branching constructs MATLAB provides a number of language constructs for branching a program's control of flow. if-end Construct : The most basic construct is: i. if , end Here the condition is a logical expression that will evaluate to either true or false (i.e., with values 1 or 0). When the logical expression evaluates to 0, the program control moves on to the next program construction. You should keep in mind that MATLAB regards A==B and A> a = 1; >> b = 2; >> if a < b, c = 3; end; >> c Electrical Engineering Department
Page 13
COMSATS IIT 14 Signals and Systems c= 3 If-else-end Construct: Frequently, this construction is elaborated with ii. if , else end In this case if condition is 0, then program2 is executed. If-elseif-end Construct: Another variation is iii. if , elseif , end Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then program2 is executed, and otherwise control is passed on to the next construction. Looping constructs i. For Loops : A for loop is a construction of the form for i= 1 : n, , end The program will repeat once for each index value i = 1, 2 .... n. Here are some examples of MATLAB's for loop capabilities: Example: The basic for loop >> for i = 1 : 5, c = 2*i end c= 2 ..... lines of output removed ... c= 10 computes and prints "c = 2*i" for i = 1, 2, ... 5. Example: For looping constructs may be nested. Here is an example of creating a matrices contents inside a nested for loop: >> for i=1:10, for j=1:10, A(i,j) = i/j; end end There are actually two loops here, with one nested inside the other; they define A(1,1), A(1,2), A(1,3) ... A(1,10), A(2,1), ... A(10,10) in that order. Electrical Engineering Department
Page 14
COMSATS IIT 15 Signals and Systems Example: MATLAB will allow you to put any vector in place of the vector 1:n in this construction. Thus the construction >> for i = [2,4,5,6,10], , end is perfectly legitimate. In this case program will execute 5 times and the values for the variable i during execution are successively, 2,4,5,6,10. i. While Loops A while loop is a construction of the form while , , end where condition is a MATLAB function, as with the branching construction. The program will execute successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is no guarantee in general that you will exit a while loop. Here is a sample program using a while loop. function l=twolog(n) % l=twolog(n). l is the floor of the base 2 % logarithm of n. l=0; m=2; while msyms a b c x f; We declared five symbolic variables. Now let’s declare an equation >> f = a*x^2+b*x+c; Then we want to substitute numerical Values for a, b, c, x. >>subs (f, {a,b,c,x}, {1,2,3,4}) ans =
27
For the details of subs command, read page 21 of the bookSymbolic MathToolbox. We could also use the sym command. The sym command lets you construct symbolic variables and expressions. Forexample, the commands x = sym('5') a = sym('6') create a symbolic variable x and substituted 5 for x and a symbolic variable a that has value 6.
Electrical Engineering Department
Page 31
COMSATS IIT 32 Signals and Systems Symbolic and Numeric Conversions Read Page 21 of the book Creating Symbolic Math Functions Read Page 28 of the book Differentiation To illustrate how to take derivatives using the Symbolic Math Toolbox, firstcreate a symbolic expression: syms x f = sin (5*x) The command diff (f) differentiates f with respect to x: ans = 5*cos(5*x) Another example: To find diff_f =
df dx
where f = e-axx3bsin(cx) and a, b and c are unspecified constants, we do the following(next page): clear; syms a b c x; f=exp(-a*x)*x^(3*b)*sin(c*x); diff_f = diff(f,x) The result is: diff_f = (3*b*x^(3*b - 1)*sin(c*x))/exp(a*x) + (c*x^(3*b)*cos(c*x))/exp(a*x) - (a*x^(3*b)*sin(c*x))/exp(a*x) Notice that the result is quite complex. To ask MATLAB to try to simplify it, type: >>diff_f_simp = simple(diff_f) Now th result is: diff_f_simp = Electrical Engineering Department
Page 32
COMSATS IIT 33 Signals and Systems (x^(3*b - 1)*(3*b*sin(c*x) + c*x*cos(c*x) - a*x*sin(c*x)))/exp(a*x)
MATLAB can take higher order differentials. For example, to find diff2_f =
d 2f dx 2
we do
>>diff2_f=diff(f,x,2) using the already defined expression for f. Note:More details on Derivative page 30-35 of the book 5)Limits The fundamental idea in calculus is to make calculations on functions as avariable “gets close to” or approaches a certain value. For example
sin( ax) lim x 0 x clear; syms x a; value = limit(sin(a*x)/x,x,0) value = a Now try the following code: value= limit(sin(x)/x,x,0) value = 1 As we know from our calculus knowledge= a and
sin( ax) = 1 lim x 0 x
sin( ax) lim x 0 x
Note: For details on Limits page 35-38 of the book 6)Integration: If f is a symbolic expression, then int(f) Electrical Engineering Department
Page 33
COMSATS IIT 34 Signals and Systems attempts to find another symbolic expression, F, so that diff(F) = f. That is,int(f) returns the indefinite integral or antiderivative of f (provided oneexists in closed form). Similar to differentiation. Indefinite integrals: For the syntax for symbolic integration, see >>help sym/int. Thus, for example, to find the indefinite integral
int_g = gdx where g = e-axsin(cx), We do clear; syms a c x; g=exp(-a*x)*sin(c*x); int_g = int(g,x)
Check this by taking >>diff_int =diff(int_g,x) This should give back g, but it doesn’t look the same because MATLAB doesn’t always give things in the simplest format. In this case, we again use the simple command >>diff_int_simp = simple(diff_int). Note that MATLAB does not add the constant of integration (“C”) customarily shown for indefinite integrals -- this you must do by adding C after the int command.
Sometimes MATLAB is not able to integrate an expression symbolically. For example, try to find fdx (where, as before, f = e-axx3bsin(cx) and a, b and c are unspecified constants). clear; symsa b c x; f = exp(-a*x)*x^(3*b)*sin(c*x); int(f,x)
When MATLAB cannot find a solution, it gives a warning message and repeats the command. When this happens, you’re out of luck.
Electrical Engineering Department
Page 34
COMSATS IIT 35 Signals and Systems
Definite integrals: For the definite integral, int_def_g =
gdx
Enter clear; syms a c x; g = exp(-a*x)*sin(c*x); int_def_g = int(g,x,-pi,pi)
When MATLAB is unable to find an analytical (symbolic) integral, such as with >>int(exp(sin(x)),x,0,1) a numerical solution can nevertheless be found using the “quad” command, e.g. >>quad('exp(sin)',0,1) Generally speaking, it is best to follow the steps below:
1. Create the function to be integrated in the MATLAB editor and save it to your Current Directory, which must also be in the path (File / Set Path). For example, for our exp(sin(x)) function: function out = func1(x) out = exp(sin(x)); end 2. Use either one of the following formats: >>quad('func1',0,1) or >>quad(@func1,0,1) Note: For details on Integration page 38-45 of the book 7)Symbolic Summation: You can compute symbolic summations, when they exist, by using the symsumcommand. For example, the p-series
sums to π2 /6 , while the geometric series
sums to 1/(1-x) , provided that |x| < 1
Electrical Engineering Department
Page 35
COMSATS IIT 36 Signals and Systems Three summations are demonstrated below: syms x k s1 = symsum(1/k^2,1,inf) s2 = symsum(x^k,k,0,inf) s1 = 1/6*pi^2 s2 = -1/(x-1) Note:For Taylor Series and other details read Page 45-47 8) Solution of Equations: The symbolic toolbox in MATLAB is capable of solving many types of equations, including non-linear ones and several simultaneous equations. See >> help solve. The steps in solving one or more equations using “solve” are: Step 1: Define the variables in the equations as symbolic using the “syms” command. Step 2: Define the equations (see the examples below). Step 3: Solve the equations using the “solve” command. Step 4: If there is more than one solution, decide which is physically reasonable and select it. Step 5: Check the solution by substituting it back into the original equation(s). We now look at some examples. Example: Find the two solutions to the classic quadratic equation, ax2 + bx + c = 0. clear all; clc; syms x y z a b c; eq = 'a*x^2+b*x+c = 0'; [x]=solve(eq,x) (Note that single quotation marks must be placed around an equation that is assigned to a variable, here eq.) As expected, we obtain two solutions. x= -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a) Suppose we want only the first. This is extracted by >>x1 = x(1) .
Electrical Engineering Department
Page 36
COMSATS IIT 37 Signals and Systems This should be done manually or using a logical operator (“if” command), because MATLAB's symbolic engine doesn't always give multiple solutions in the same order. What is x(1) now could be x(2) in a subsequent trial. Example: Find the solution to e2x=3y: clear all; clc; syms x y; eq = 'exp(2*x) = 3*y'; [x] = solve(eq,x)
We use a similar procedure to solve simultaneous equations. First, let us look at a set of linear equations, and then non-linear equations. Example: Find the solution to the following set of linear equations: 2x-3y+4z = 5 y+4z+x = 10 -2z+3x+4y = 0 syms x y z; eq1 = '2*x-3*y+4*z = 5' ; eq2 = 'y+4*z+x = 10' ; eq3 = '-2*z+3*x+4*y = 0' ; [x,y,z] = solve(eq1,eq2,eq3,x,y,z) Notice that we did not have to enter x, y and z in any particular order in defining the equation variables (unlike the numerical MATLAB method using matrices with \ or inv). However, the variables in the output are in alphabetical order, regardless of how they are written in the command. So take care to list the variables in the brackets in alphabetical order. (For example, if you use [z,x,y] rather than [x,y,z] in the above example the result produced for z is actually x, that for x is actually y, and that for y is actually z.)
Again, the results may be symbolic and require conversion to numeric form for subsequent
calculations:
NOTE: It is a self study practical and includes no task to be submitted. However, coming 3 to 4 labs are based on this lab, therefore, special attention should be paid to this lab.
Electrical Engineering Department
Page 37
COMSATS IIT 38 Signals and Systems
Lab 7: “Implementation of convolution integral” In this lab, you will learn about the following topics: Convolution Integral
Finding Convolution Integral
Convolution Integral: Convolution Integral means convolution of two CT signals. We have discussed it in much detail in the class. Now it’s time to implement it in Matlab so that you could sharpen your concepts. I will say few words about the CT convolution just to refresh the concepts. Convolution helps to determine the effect of the system on an input signal. The shifting property of impulses tells us that a signal can be decomposed into an infinite sum (integral) of scaled and shifted impulses. Knowing how a system affects a single impulse, and by understanding the way a signal is comprised of scaled and summed impulses, it seems reasonable that it should be possible to scale and sum the impulse responses of a system in order to determine what output signal will results from a particular input.
Finding Convolution Integral: We will discuss two methods: Method 1 (Numerical Method) Step 1: Define/Sketch x (τ) and h (τ). Step 2: The impulse response, h (τ) time-reversed or folded to obtain h (-τ). Step 3: Then h (- τ) shifted by t to form h (t - τ) = h [-(τ - t)] which is a function of τ with parameter t. Begin with shift t large and negative, i.e., shift h (- τ ) to the far left on the time axis. Step 4: The signal x (τ) and h (t - τ) are multiplied together for all values of τ with t fixed at some value. Step 5: The product x (τ) h (t- τ) is integrated over all τ to produce a single output value y (t). Step 6: For Calculating the response of the system over all instants of time, repeat steps 3to 5 till response at all time instants (t = -∞ to ∞) is obtained.
Electrical Engineering Department
Page 38
COMSATS IIT 39 Signals and Systems
Method 2 (Symbolic Math Toolbox) Step 1: Generate x ( τ) and h (t - τ). (Use syms) Step 2: Multiply x ( τ) and h (t - τ). Step 3: Find out limits of integration and use int to integrate product x ( τ) h (t- τ) withrespect to τ to produce output, y (t) (Recall pretty, simplify, collect and subs from the book that has been uploaded on the portal). Step 4: Use ezplot to sketch x (t), h (t) and y (t). Use subplot to show CT signals and their convolution in single figure. Let’s understand all this with the help of an example. Example 1: Compute the convolution integral y(t)=x(t)*h(t) of the following pairs of signals: x(t) = e
Using Method 1:
3t
u(t)
h(t) = u(t + 3)
Declare three functions in the matlab editor separately Save them(don’t run them) Then run the function whose name is example1 function [y ] = unit( t ) y=0.*(t0); end
function [y] = conv_lab(x,h) m=length(x); n=length(h); t=m+n-1; X=[x,zeros(1,n-1)]; H=[h,zeros(1,m-1)]; for i=1:(length(X)) y(i)=X(1:i)*H(i:-1:1)'; end end
Electrical Engineering Department
Page 39
COMSATS IIT 40 Signals and Systems
function [] = example1() t=-5:0.001:5; x=exp(-3*t).*unit(t); subplot(2,2,1); plot(t,x); xlabel('time(t)'); ylabel('exp(-3*t)*u(t)'); title('x(t)'); axis([-5 5 -2 2]); h=unit(t+3); subplot(2,2,2); plot(t,h); xlabel('time(t)'); ylabel('u(t+3)'); title('h(t)'); axis([-5 5 -2 2]); y=conv_lab(x,h); subplot(2,1,2); plot(y); xlabel('time(t)'); ylabel('x(t)*h(t)'); title('x(t)*h(t)'); end
Results: h(t) 2
1
1 u(t+3)
exp(-3*t)*u(t)
x(t) 2
0 -1
0 -1
-2 -5
0 time(t)
5
-2 -5
0 time(t)
5
x(t)*h(t) 400
x(t)*h(t)
300 200 100 0
0
0.5
1
1.5 time(t)
Electrical Engineering Department
2
2.5 4
x 10
Page 40
COMSATS IIT 41 Signals and Systems
Task: Compute the convolution integral y(t)=x(t)*h(t) of the following pairs of signals:
Electrical Engineering Department
Page 41
COMSATS IIT 42 Signals and Systems Solution: Place a cutting of your printed code in the box given below:
Electrical Engineering Department
Page 42
COMSATS IIT 43 Signals and Systems Paste your final figures here, or attach an addition page if required
Electrical Engineering Department
Page 43
COMSATS IIT 44 Signals and Systems
Lab 8: “Implementation of Fourier Analysis and Fourier Synthesis”
Today’s Lab is about Continuous Time Fourier series i.e. Fourier analysis
Fourier synthesis
Fourier analysis: In mathematics, Fourier analysis is the study of the way general functions may be represented or approximated by sums of simpler trigonometric functions the subject of Fourier analysis encompasses a vast spectrum of mathematics. In the sciences and engineering, the process of decomposing a function into simpler pieces is often called Fourier analysis, while the operation of rebuilding the function from these pieces is known as Fourier synthesis. Example: Fouier Analysis of a square wave (Check example 3.5 of the book for detail) Code: function [] = fourier() clc; clear all; syms a0 ak k T0 T1 T2 t w0 y T0=4*T1; w0=(2*pi)/T0; % calculate the DC comonent a0 a0=1/T0*int(1,t,-T1,T1); a0=simplify(a0); %calculate the kth harmonic ak ak=1/T0*int(exp(-1i*k*w0*t),t,-T1,T1); ak=simplify(ak); index=[-9:11]; for i=1:1:21 if i-10==0 y(1,10)=subs(a0,k,i-10); else y(1,i)=subs(ak,k,i-10); end end y = double(y); %axis([-20 20 -2 2]); display(size(index)); display(size(y)); axis([-20 20 -5 5]); stem(index,y); end
Electrical Engineering Department
Page 44
COMSATS IIT 45 Signals and Systems
Fourier Synthesis Let us implement the synthesis equation i.e. add the Fourier components as follows: x(t) = a0 x(t) = a-1e-jw0t + a0 + a1ejw0t x(t) = a-2e-j2w0t + a-1e-jw0t + a0 + a1ejw0t + a2ej2w0t . . . . Until we get a close approximated shape of x (t). function [] = fourier_synthesis( ) clc; clear all; x=1/2; T=1; w0=(2*pi)/T; t=-1:0.001:1; for k=1:20 ak=sin(k*pi/2)/(k*pi); x=x+ak*(exp(1i*k*w0*t)+exp(-1i*k*w0*t)); end plot(t,x); end
DC + first harmonic Results: 1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
DC + first + third harmonics
Electrical Engineering Department
Page 45
COMSATS IIT 46 Signals and Systems
1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
-0.4
-0.2
0
-0.2
0
0.2
0.4
0.6
0.8
1
1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
Electrical Engineering Department
-0.4
0.2
0.4
0.6
0.8
1
Page 46
COMSATS IIT 47 Signals and Systems First 10 harmonics 1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
-0.4
-0.2
0
0.2
-0.2
0
0.2
0.4
0.6
0.8
1
20 harmonics 1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
Electrical Engineering Department
-0.4
0.4
0.6
0.8
1
Page 47
COMSATS IIT 48 Signals and Systems 50 Harmonics 1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
-0.4
-0.2
0
0.2
-0.2
0
0.2
0.4
0.6
0.8
1
200 Harmonics 1.2
1
0.8
0.6
0.4
0.2
0
-0.2 -1
-0.8
-0.6
-0.4
0.4
0.6
0.8
1
Task: Implement a complete harmonic set for Triangular wave. Electrical Engineering Department
Page 48
COMSATS IIT 49 Signals and Systems Solution: Place a cutting of your printed code in the box given below:
Electrical Engineering Department
Page 49
COMSATS IIT 50 Signals and Systems Paste your final figures here, or attach an addition page if required
Electrical Engineering Department
Page 50
COMSATS IIT 51 Signals and Systems Lab 09 “Continuous Time Fourier Transform Implementation in Matlab” The basic objective of this Lab is to make the students familiar with Fourier transform fusing Matlab. In Matlab a built in function for ‘fft’ exists which is the implementation of Fast Fourier transform, however, there is no function available for CTFT. Help on these commands is available in Matlab help directory. 1. 2. 3. 4. 5. 6. 7. 8.
Open M-file or M-Book. The first step is to generate a CTFT function. Thus, use the reserve word function and name you are choosing for your code should also be the name of the M-file. There should be two input arguments two the function t, x(t). While two output parameters ω, X(jω). Note: the length of ω and n are distinguished and not interdependent. Now two generate X(jω), we would be using vectors multiplications. X(jω)=∫ ? (?)? ?? ? ? ?;thus we require three vectors x, ω and t. Their transpose multiplication would generate the required CTFT. Now make another M-File that would act as the calling module, save it by any useful name but remember not to start the name by any numeric digit, do not use any special character other than under-the-score ( _ ) and also remember not to give any space in the name. Previously, generated unit step function would be quite a help in this Lab. function [w,X]=CTFT(t,x) w= -pi:0.01:pi; ee=exp(-j*w'*t); w=w./pi*1000; X=x*ee';
The above function will calculate CTFT of any given signal. Task: Generate a square wave and check out its transform. Also view the frequency spectrum a triangular wave. Generate a sinusoidal of Fn= Your Roll Number and Fs= 2000. And view its spectrum.
Electrical Engineering Department
Page 51
COMSATS IIT 52 Signals and Systems Solution: Place a cutting of your printed code in the box given below:
Electrical Engineering Department
Page 52
COMSATS IIT 53 Signals and Systems Paste your final figures here, or attach an addition page if required
Electrical Engineering Department
Page 53
COMSATS IIT 54 Signals and Systems
Lab 10 “Discrete Time Fourier Transform Implementation in Matlab” The basic objective of this Lab is to make the students familiar with Discrete Fourier trasnform using Matlab. In Matlab a built in function for fft exists, however, there is no function available for DTFT.
Help on these commands is available in Matlab help directory. 9. 10. 11. 12. 13. 14. 15. 16.
Open M-file or M-Book. The first step is to generate a DTFT function. Thus, use the reserve word function and name you are choosing for your code should also be the name of the M-file. There should be two input arguments two the function n, x[n]. While two output parameters ω, X(ejω). Note: the length of ω and n are distinguished and not interdependent. Now two generate X(ejω), we would be using vectors multiplications. X(ejω)=Σx[n] ejωn ;thus we require three vectors x, ω and n. Their transpose multiplication would generate the required DTFT. Now make another M-File that would act as the calling module, save it by any useful name but remember not to start the name by any numeric digit, do not use any special character other than under-the-score ( _ ) and also remember not to give any space in the name. Previously, generated unit step function would be quite a help in this Lab.
Example: close all; n=-100:100; unit=(sign(n+eps)+1)/2; g=(sign(n-7+eps)+1)/2; h=(1/7)*(unit-g); [w,H]=F_DtFt(n,h); figure,subplot(3,1,1),stem(n,h);title 'h[n]' subplot(3,1,2),plot(w,abs(H));title 'Absolute or Magnitude of [H]' subplot(3,1,3),plot(w,angle(H));title 'Angle of [H]' a=sin((pi/3)*n)./(pi*n); x=[a(1:100) 1 a(102:201)]; figure,subplot(3,1,1),stem(n,x);title 'x[n]' [w,X]=F_DtFt(n,x); subplot(3,1,2),plot(w,abs(X));title 'Absolute or Magnitude of dtft of [X]' subplot(3,1,3),plot(w,angle(X));title 'Angle of dtft of [X]' N=[2*n(1,1):2*n(1,length(n))]; y=conv(x,h); figure,stem(N,y);title 'y[n]' [w,Y]=F_DtFt(N,y); subplot(2,1,1),plot(w,abs(Y));title 'Absolute or Magnitude of Y[e(jw)] By convolution' Electrical Engineering Department
Page 54
COMSATS IIT 55 Signals and Systems subplot(2,1,2),plot(w,angle(Y));title 'Angle of Y[e(jw)] By convolution' figure Y1=X.*H; subplot(2,1,1),plot(w,abs(Y1));title 'Absolute or Magnitude of Y1[e(jw)] By Multiplication' subplot(2,1,2),plot(w,angle(Y1));title 'Angle of Y1[e(jw)] By Multiplication' Calling Function: function [w,X]=F_DtFt(n,x); w=-20:0.01:20; e=(exp(j*w'*n))'; X=x*e; Output:
h[n] 0.2 0.1 0 -100
-80
-60
-40
-20
0
20
40
60
80
100
Absolute or Magnitude of [H] 1 0.5 0 -20
-15
-10
-5
0
5
10
15
20
5
10
15
20
Angle of [H] 5 0 -5 -20
-15
-10
Electrical Engineering Department
-5
0
Page 55
COMSATS IIT 56 Signals and Systems
x[n] 1 0 -1 -100
-80
-60
-40
-20
0
20
40
60
80
100
Absolute or Magnitude of dtft of [X] 2 1 0 -20
-15
-10
-5
-17
2
0
5
10
15
20
5
10
15
20
10
15
20
10
15
20
Angle of dtft of [X]
x 10
0 -2 -20
-15
-10
-5
0
Absolute or Magnitude of Y[e(jw)] By convolution 2 1.5 1 0.5 0 -20
-15
-10
-5
0
5
Angle of Y[e(jw)] By convolution 4 2 0 -2 -4 -20
-15
-10
Electrical Engineering Department
-5
0
5
Page 56
COMSATS IIT 57 Signals and Systems Absolute or Magnitude of Y1[e(jw)] By Multiplication 2 1.5 1 0.5 0 -20
-15
-10
-5
0
5
10
15
20
10
15
20
Angle of Y1[e(jw)] By Multiplication 4 2 0 -2 -4 -20
-15
-10
-5
0
5
Task: Generate the following signals and provide a detailed analysis of it time and frequency spectrum. ? [? ] = sin ? ?7
2? ? ? 5
? [? ] = ? 3 ? (? [? + 4] − ? [? − 4])
Electrical Engineering Department
Page 57
COMSATS IIT 58 Signals and Systems Solution: Place a cutting of your printed code in the box given below:
Electrical Engineering Department
Page 58
COMSATS IIT 59 Signals and Systems Paste your final figures here, or attach an addition page if required
Electrical Engineering Department
Page 59