Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
102 views64 pages

Signal and System Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

ECE, JIIT NOIDA ODD/EVEN SEMESTER

Experiment - 1
Aim: Introduction to MATLAB and its various applications.

What is MATLAB?

MATLAB® is a high-performance language for technical computing. It integrates


computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.

Typical uses include Math and computation Algorithm development, Data


acquisition Modelling, simulation, and prototyping Data analysis, exploration, and
visualization Scientific and engineering graphics Application development, including
graphical user interface building.

MATLAB is an interactive system whose basic data element is an array that does
not require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations.
MATLAB®

(Programming Language)

User-Written Functions

Built -in Functions


Computations
Graphics External Interfaces
 Linear Algebra
 2-D Graphics  Data Analysis
Interface With C, Java, and
 3-D Graphics  Signal Processing Fortran Programmes
 Color and Lighting  Polynomials & Interpolation
 Animation  Integration
 Solutions of ODEs

Toolboxes

 Signal Processing
 Image Processing
 Statistics
 Communications
 Symbolic Mathematics etc.

1
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Theory:

A. MATLAB Basics

1. MATLAB Windows
 MATLAB Desktop – Double Click on the MATLAB program icon to launch
MATLAB. This is where MATLAB puts you when you launch it. It consists
of the following sub-windows.
a. Command Window – This is main window. It is characterized by the
MATLAB command prompt (>>).Use the Command Window to enter
variables and to run functions and M-file scripts. All commands,
including those for running user-written programs, are typed in this
window at the MATLAB command prompt. To execute a command,
you must press enter or return at end.
b. Current Directory – All the files from the current directory are listed
here. You have several options of what you can do with file once you
select it using mouse. You can run, M-files, rename them, delete them,
etc., using right click of mouse.
c. Workspace – The MATLAB workspace consists of the set of variables
(named arrays) built up during a MATLAB session and stored in
memory. You add variables to the workspace by using functions,
running M-files, and loading saved workspaces.
d. Command History - Statements you enter in the Command Window
are logged in the Command History. From the Command History, you
can view previously run statements, as well as copy and execute selected
statements. You can also create an M-file from selected statements.
 Figure Window - MATLAB directs graphics output to a window that is separate
from the Command Window. In MATLAB this window is referred to as a figure.
The characteristics of this window are controlled by your computer's windowing
system and MATLAB figure properties. Graphics functions automatically create
new figure windows if none currently exist. If a figure already exists, MATLAB
uses that window. If multiple figures exist, one is designated as the current figure
and is used by MATLAB (this is generally the last figure used or the last figure
you clicked the mouse in).
 Editor Window - Use the Editor/Debugger to create and debug M-files, which
are programs you write to run MATLAB functions. The Editor/Debugger
provides a graphical user interface for text editing, as well as for M-file
debugging. To create or edit an M-file use File  New or File  Open, or use
the edit function.

2
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Editor
Workspace
Command Window
Window

Figure
Command
Window
History

MATLAB

Desktop
Window
Figure 1. The MATLAB environment consists of MATLAB Desktop, a figure
window, and an editor window. The figure window and the editor window appear
only when invoked with appropriate commands.

2. Input-Output
 Data Type - There are many different types of data that you can work with in
MATLAB. You can build matrices and arrays of floating-point and integer data,
characters and strings, logical true and false states, etc. You can also develop your
own data types using MATLAB classes. Two of the MATLAB data types,
structures and cell arrays, provide a way to store dissimilar types of data in the
same array.
There are 15 fundamental data types in MATLAB. Each of these data types is in
the form of a matrix or array. This matrix or array is a minimum of 0-by-0 in size
and can grow to an n-dimensional array of any size.

3
ECE, JIIT NOIDA ODD/EVEN SEMESTER

 Dimensioning – automatic in MATLAB.


 Case sensitivity – Case Sensitive, MATLAB requires an exact match for variable
names. For example, if you have a variable a, you cannot refer to that variable as
A. With respect to functions, filenames, objects, and classes on the search path or
in the current directory, MATLAB prefers an exact match with regard to case.
MATLAB runs a function if you do not enter the function name using the exact
case, but displays a warning the first time you do this.
 Output Display – The output of every command is displayed on the command
window unless MATLAB is directed otherwise. A semicolon at the end of a
command suppresses output.
Output Format - The number of digits displayed is not related to the accuracy.
The display format is set by typing format type on the command line, type
format short e for scientific notation with 5 decimal places, format long e for
scientific notation with 15 significant decimal places and format bank for
placing two significant digits to the right of the decimal, default is format short.

 Command History - The Command History window presents a log of the


statements most recently run in the Command Window. Use the arrow, tab, and
control keys on your keyboard to recall, edit, and reuse functions you typed
earlier. Instead of retyping the entire line, press the up arrow key. The previously
typed line is redisplayed. Use the left arrow key to move the cursor, edit if
required, and press Enter or Return to run the line. Repeated use of the up arrow
key recalls earlier lines, from the current and previous sessions. Using the up
arrow key, you can recall any line maintained in the Command History window.
Similarly, specify the first few characters of a line you entered previously and
press the up arrow key to recall the previous line.

4
ECE, JIIT NOIDA ODD/EVEN SEMESTER

3. File Types
 M-files - MATLAB provides a full programming language that enables you to
write a series of MATLAB statements into a file and then execute them with a
single command. You write your program in an ordinary ASCII text file, giving
the file a name of filename.m. The term you use for filename becomes the new
command that MATLAB associates with the program. The file extension of
.m makes this a MATLAB M-file. M-files can be scripts that simply execute a
series of MATLAB statements, or they can be functions that also accept input
arguments and produce output.
 Mat – files - The save command in MATLAB saves the MATLAB arrays
currently in memory to a binary disk file called a MAT-file. The term MAT-file is
used because these files have the extension .mat. The load command performs the
reverse operation. It reads the MATLAB arrays from a MAT-file on disk back
into MATLAB workspace. MAT-files provide a convenient mechanism for
moving your MATLAB data between different platforms and for importing and
exporting your data to other stand-alone MATLAB applications.
 Fig – files – Binary files with a .fig extension that can be opened again in
MATLAB as figures. Such files are created by saving a figure in this format using
save or save as options from File menu of Figure window. This contains all the
information required to recreate the figure. To open use open filename. fig.
 P – files - You can save a preparsed version of a function or script, called P-code
files, for later MATLAB sessions using the pcode function. If you develop an
application that other people can use but you do not want to give source code,
then you give them the corresponding p- files.
 Mex – files – are MATLAB callable FORTTRAN and C programs, with a .mex
extension to the filenames.

4. Conversing with MATLAB and General Commands

who - MATLAB replies with the variables in your workspace.


whos - MATLAB replies with the variables in your workspace with their size.
what - MATLAB replies with the current directory and MATLAB files in the
directory
clear – clears variables from environment
clear all - clears all variables from environment
clear a b - look at workspace, the variables a and b are gone
clc/home - clears the cluttered command window.

5
ECE, JIIT NOIDA ODD/EVEN SEMESTER

close all – closes all figure windows


clf – clears figure window

pwd – shows current working directory


cd - changes current working directory
dir/ls – lists content of current working directory
Path – gets or sets MATLAB search path
Edit path – edits MATLAB search path
copyfile – copies a file
mkdir – creates a directory
help – Lists topic on which help is available. (The most important function for
learning MATLAB on your own).
help function name – Lists help on function usage, related functions, and links to
help document. To get info on how to use function)
doc topic - To get a nicer version of help with examples and easy-to-read
descriptions
doc + search tab - To search for a function by specifying keywords
look for string– lists help topic containing string
demo – runs the demo program
load - To load variable bindings into the environment
save - To save variables to a file
Control + C – local abort, terminate current command execution
Quit/Exit – exits MATLAB

B. Scripts

Scripts are collection of command executed in sequence, written in editor and


saved as M-files (.m extension). A script file is executed by typing its name in at
command prompt. All of the MATLAB examples in this textbook are contained in M-
files that are available at the Mathworks ftp site.

MATLAB requires that the M-file must be stored either in the working directory or in a
directory that is specified in the MATLAB path list. For example, consider using
MATLAB on a PC with a user-defined M-file stored in a directory called
"\MATLAB\MFILES". Then to access that M-file, either change the working directory
by typing cd\matlab\mfiles from within the MATLAB command window or by adding
the directory to the path. Permanent addition to the path is accomplished by editing the
\MATLAB\matlabrc.m file, while temporary modification to the path is accomplished
by typing path(path,'\matlab\mfiles') from within MATLAB.

6
ECE, JIIT NOIDA ODD/EVEN SEMESTER

C. Making and Manipulating Variables

MATLAB is a weakly typed language and there is No need to initialize variables.

MATLAB supports various types, the most often used are


» 3.84 64-bit double (default)

» ‘a’ 16-bit char

Other types are also supported: complex, symbolic, 16-bit and 8 bit integers, etc.

 First character of variable names must be a LETTER after that, any combination
of letters, numbers and _.
 Variable names are CASE SENSITIVE (a is different from A)
Some examples of Built-in variables

 i and j can be used to indicate complex numbers


 pi has the value 3.1415926…
 ans stores the last unassigned value (like on a calculator)
 Inf and -Inf are positive and negative infinity
 NaN represents „ Not a Number‟

A variable can be given a value explicitly

» a = 10 shows up in workspace

Or as a function of explicit values and existing variables

» c = 1.3*45-2*a

To suppress output, end the line with a semicolon

» cool = 13/3;

Like other programming languages, arrays are an important part of MATLAB

7
ECE, JIIT NOIDA ODD/EVEN SEMESTER

• Two types of arrays

o matrix of numbers (either double or complex)


o cell array of objects (more advanced data structure)

Row vector: comma or space separated values between brackets

» row = [1 2 5.4 -6.6] or » row = [1, 2, 5.4, -6.6];

Command Window: >> row = [1 2 5.4 -6.6]

row =

1.0000 2.0000 5.4000 -6.6000

Workspace:

Column vector: semicolon separated values between brackets

» column = [4; 2; 7; 4]

Command window: >> column = [4; 2; 7; 4]

column =

Workspace:

8
ECE, JIIT NOIDA ODD/EVEN SEMESTER

You can tell the difference between a row and a column vector by:

o Looking in the workspace


o Displaying the variable in the command window
o Using the size function

>> size(row) >> size(column)

ans = ans =

1 4 4 1
To get a vector's length, use the length function

>>length (row) >> length(column)


ans = ans =

4 4

Make matrices like vectors

 Element by element >> a= [1 2; 3 4]


a=

1 2
3 4

 By concatenating vectors or matrices (dimension matters)

9
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»a = [1 2];

»b = [3 4];

»c = [5; 6];

»d = [a; b];

»e = [d c];

»f = [[e e] ; [a b a]];

»str = ['Hello, I am ' 'John']; Strings are character vectors

Basic Scalar Operations

 Arithmetic operations ( + ,- , *, /)
» 7/45

» (1+i) * (2+i)

»1/0

»0/0

 Exponentiation (^)
» 4^2

» (3+4*j) ^ 2

 Complicated expressions, use parentheses


» ((2 + 3) * 3) ^ 0.1

 Multiplication is NOT implicit given parentheses


» 3 (1 + 0.7) gives an error

 The transpose operators turn a column vector into a row vector and vice versa
» a = [1 2 3 4+i]

» transpose(a)

»a'

»a.'

The ' gives the Hermitian-transpose, i.e. transposes and conjugates all complex numbers

10
ECE, JIIT NOIDA ODD/EVEN SEMESTER

For vectors of real numbers .' and ' give same result.

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;

Built-in Functions

MATLAB has an enormous library of built-in functions

• Call using parentheses –passing parameter to function

»sqrt(2)

»log(2), log10(0.23)

»cos(1.2), atan(-.8)

»exp(2+4*i)

»round(1.4), floor(3.3), ceil(4.23)

»angle(i); abs(1+i);

Note: Explore these functions using help or doc

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.

Addition and Subtraction

Addition and subtraction are element-wise; sizes must match (unless one is a scalar):

• The following would give an error

» c = row + column

• Use the transpose to make sizes compatible

»c = row’+ column

»c = row + column’

• Can sum up or multiply elements of vector

11
ECE, JIIT NOIDA ODD/EVEN SEMESTER

» s = sum (row);

» p = prod (row);

Element-Wise Functions

•All the functions that work on scalars also work on vectors

»t = [1 2 3];

»f = exp(t); is the same as »f = [exp(1) exp(2) exp(3)];

•If in doubt, check a function‟s help file to see if it handles vectors elementwise

•Operators (* / ^) have two modes of operation

o element-wise
o standard

Operators: element-wise

•To do element-wise operations, use the dot: „.‟(.* , ./ , .^). BOTH dimensions
must match (unless one is scalar)!

»a = [1 2 3]; b = [4; 2; 1];

»a .* b, a./ b, a. ^ b all errors

»a .*b', a./ b’, a .^ (b’) all valid

Operators: standard

•Multiplication can be done in a standard way or element-wise

•Standard multiplication (*) is either a dot-product or an outer-product

•Standard exponentiation (^) can only be done on square matrices or scalars

•Left and right division (/ \) is same as multiplying by inverse

Automatic Initialization

•Initialize a vector of ones, zeros, or random numbers

»o = ones(1,10) % row vector with 10 elements, all 1

12
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»z = zeros(23,1) % column vector with 23 elements, all 0

»r = rand(1,45) % row vector with 45 elements (uniform [0,1])

»n = nan(1,69) % row vector of NaNs (useful for representing uninitialized


variables)

The general function call is:

>> var = zeros(M,N); where M is Number of rows and N is Number of columns.

Note: Explore these functions using help or doc

To initialize a linear vector of values use linspace

»a = linspace (0, 10 ,5) % starts at 0, ends at 10 (inclusive), 5 values

• Can also use colon operator (:)

»b = 0:2:10 % starts at 0, increments by 2, and ends at or before 10

% increment can be decimal or negative

»c = 1:5 % if increment isn‟t specified, default is 1

•To initialize logarithmically spaced values use logspace, similar to linspace, but see
help

Vector Indexing

•MATLAB indexing starts with 1, not 0

•a(n) returns the nth element.

•The index argument can be a vector. In this case, each element is looked up individually,
and returned as a vector of the same size as the index vector.

»x = [12 13 5 8];
»a = x (2:3); a = [13 5];
»b = x (1: end-1); b = [12 13 5];
Matrix Indexing

•Matrices can be indexed in two ways

o using subscripts(row and column)


o using linear indices(as if matrix is a vector)
•Picking submatrices

13
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»A = rand(5) % shorthand for 5x5 matrix

»A(1:3,1:2) % specify contiguous submatrix

»A([1 5 3], [1 4]) % specify rows and columns

To select rows or columns of a matrix, use the:

>> c = [12 5; -2 13]

c=

12 5

-2 13

» d = c(1, :) >> e = c(:, 2) >> c (2, :) = [3 6]

d= e= c=

12 5 5 12 5

13 3 6

% replaces second row of


c

MATLAB contains functions to help you find desired values within a vector or matrix

»vec = [5 3 1 9 7]

•To get the minimum value and its index:

»[minVal, minInd] = min(vec); % max works the same way

•To find any the indices of specific values or ranges

»ind = find(vec == 9);

»ind = find(vec > 2 & vec < 6); %find expressions can be very complex,

•To convert between subscripts and indices, use ind2sub, and sub2ind. Use help.

D. Functions

User-defined Functions

14
ECE, JIIT NOIDA ODD/EVEN SEMESTER

• Functions look exactly like scripts, but for ONE difference, Functions must have a
function declaration

Function
Declaration

O/Ps Inputs

Help
Files

Some comments about the function declaration

No need for return: MATLAB 'returns' the variables whose names match those in the
function declaration

•Variable scope: Any variables created within the function but not returned disappear
after the function stops running

E. Flow Control

Relational Operators < > <= >= == ~=

15
ECE, JIIT NOIDA ODD/EVEN SEMESTER

•MATLAB uses mostly standard relational operators

 equal ==
 notequal ~=
 greater than >
 less than <
 greater or equal >=
 less or equal <=
•Logical operators elementwise short-circuit (scalars)

 And & &&


 Or | ||
 Not ~
 Xor xor
 All true all
 Any true any
•Boolean values: zero is false, nonzero is true

•See help . for a detailed list of operators

if/else/elseif - Execute statements if additional condition is true

Syntax

if expression1

statements1

elseif expression2

statements2

end

Description

If expression1 evaluates as false and expression2 as true, MATLAB executes the one or
more commands denoted here as statements2.

16
ECE, JIIT NOIDA ODD/EVEN SEMESTER

A true expression has either a logical 1 (true) or nonzero value. For nonscalar
expressions, (for example, is matrix A less then matrix B), true means that every element
of the resulting matrix has a true or nonzero value.

For - Execute block of code specified number of times

Syntax

for variable = expression

statements

end

Description

The columns of the expression are stored one at a time in the variable while the following
statements, up to the end, are executed.

In practice, the expression is almost always of the form scalar: scalar, in which case its
columns are simply scalars.

The scope of the “for” statement is always terminated with a matching end.

while - Repeatedly execute statements while condition is true

Syntax

while expression

statements

end

Description

while repeats statements an indefinite number of times. The statements are executed
while the real part of expression has all nonzero elements. expression is usually of the
form expression relational operator expression where relational operator is ==, <, >, <=,
>=, or ~=. The scope of a while statement is always terminated with a matching end.

F. Plotting

»x = linspace(0,4*pi,10);

»y = sin(x);

17
ECE, JIIT NOIDA ODD/EVEN SEMESTER

•Plot values against their index

»plot(y);

•Usually we want to plot y versus x

»plot( x , y);

Plot generates dots at each (x, y) pair and then connects the dots with a line

•To make plot of a function look smoother, evaluate at more points

»x = linspace (0, 4*pi, 1000);

»plot(x, sin(x));

•x and y vectors must be same size or else you‟ll get an error

»plot ([1 2], [1 2 3]) error!

•Can change the line color, marker style, and line style by adding a string argument

»plot (x, y, ’k.-’);

•Can plot without connecting the dots by omitting line style argument

»plot (x, y, ’.’)

•Look at help plot for a full list of colors, markers, and linestyles

Some Other Useful Commands:

xlabel, ylabel, title, xlim, ylim, grid, axis, hold, stem

Cartesian Plots Commands: plot, semilogx, semilogy, loglog

3D Line Plot Command: plot3, surf, contour, quiver, xlim, ylim, zlim

subplot for Multiple Plots in one Figure

G. Solving Equations

Systems of Linear Equations

•Given a system of linear equations

x + 2y - 3z = 5, -3x – y + z = -8, x–y+z=0

•Construct matrices so the system is described by Ax = b

18
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»A = [1 2 -3; -3 -1 1; 1 -1 1];

»b = [5; -8; 0];

•And solve with a single line of code!

»x = A\b; % x is a 3x1 vector containing the values of x, y, and z

•The \ will work with square or rectangular systems.

•Gives least squares solution for rectangular systems. Solution depends on whether the
system is over or underdetermined.

Given a matrix

»m = [1 2 -3; -3 -1 1; 1 -1 1];

•Calculate the rank of a matrix

»r = rank(m); % the number of linearly independent rows or columns

•Calculate the determinant

»d = det(m); % m must be square, if determinant is nonzero, matrix is invertible

•Get the matrix inverse

»E = inv(m); % if an equation is of the form A* x = b with A a square matrix, x =


A\b is the same as x = inv(A) * b

Polynomials

•Many functions can be well described by a high-order polynomial

•MATLAB represents polynomials by a vector of coefficients

if vector P describes a polynomial ax3 + bx2 + cx + d

•P = [1 0 -2] represents the polynomial x2 - 2

•P = [2 0 0 0] represents the polynomial 2x3

P is a vector of length N+1 describing an N-th order polynomial

•To get the roots of a polynomial

» r = roots(P) % r is a vector of length N

•Can also get the polynomial from the roots

19
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»P = poly(r) % r is a vector length N

Numerical Differentiation

•MATLAB can 'differentiate' numerically

»x = 0:0.01:2*pi;

»y = sin(x);

»dydx = diff(y) ./ diff(x); % diff computes the first difference

•Can also operate on matrices

»mat = [1 3 5; 4 8 6];

»dm = diff(mat,1,2) % first difference of mat along the 2nddimension, dm=[2 2;4 -
2]

Numerical Integration

•MATLAB contains common integration methods

•Adaptive Simpson's quadrature (input is a function)

Write a function ‘ y = myFun(x)’ where y = cos (exp(x) +x.^2 - 1)

»q1 = quad ('myFun', 0, 10); % q1 is the integral of the function myFun from 0 to
10

»q2 = quad (@(x) sin(x)*x, 0, pi) % q2 is the integral of sin(x)*x from 0 to pi

See function handle

•Trapezoidal rule (input is a vector)

»x = 0:0.01:pi;

»z = trapz(x, sin(x)); %z is the integral of sin(x) from 0 to pi

H. Data Structures

We have used 2D matrices

 Can have n-dimensions


 Every element must be the same type (ex. integers, doubles, characters…)
 Matrices are space-efficient and convenient for calculation
 Large matrices with many zeros can be made sparse:

20
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»a = zeros(100); a(1,3) =10; a(21, 5) = pi; b = sparse(a);

• Sometimes, more complex data structures are more appropriate

 Cell array: it's like an array, but elements don't have to be the same type
 Structs: can bundle variable names and values into one structure

– Like object oriented programming in MATLAB

I. Symbolics

Symbolic Variables
•Symbolic variables are a type, like double or char
•To make symbolic variables, use sym
»a=sym ('1/3');
»b=sym ('4/5');
»mat=sym ([1 2;3 4]); % fractions remain as fractions
»c=sym ('c', 'positive'); % can add tags to narrow down scope
% see help sym for a list of tags
•Or use syms
» syms x y real % shorthand for x=sym ('x', 'real'); y=sym ('y', 'real');
Symbolic Expressions

• Multiply, add, divide expressions

»d = a*b % does 1/3*4/5=4/15;

»expand ((a-c) ^ 2); % multiplies out

»factor (ans) % factors the expression

»matInv = inv(mat) % Computes inverse symbolically

Cleaning up Symbolic Statements

»pretty (ans) % makes it look nicer

»collect (3*x+4*y-1/3*x^2-x+3/2*y) % collects terms

»simplify (cos(x) ^ 2+sin(x)^2) % simplifies expressions

»subs (‘c^2’, c, 5) % Replaces variables with numbers or expressions.

To do multiple substitutions pass a cell of variable names followed by a cell of values

21
ECE, JIIT NOIDA ODD/EVEN SEMESTER

»subs(‘c^2’, c, x/7)

POST LAB EXERCISE

For problems 1- 4, write a script called simpleProblems.m and put all the commands in
it. Separate and label different problems using comments.

1. Scalar variables. Make the following variables

a. a = 10

b. b = 2.5 ×10 23

c. c = 2 + 3i , where i is the imaginary number

d. d = ej 2ð /3 , where j is the imaginary number and e is Euler‟s number (use exp,


pi)

2. Vector variables. Make the following variables

3. Matrix variables. Make the following variables

22
ECE, JIIT NOIDA ODD/EVEN SEMESTER

f. Make fMat be a 5x3 matrix of random integers with values on the range -3 to 3 (use
rand and floor or ceil).

4. Common functions and indexing.

5. Plotting multiple lines and colors. Open a script and name it twoLinePlot.m
To plot a sine wave and a cosine wave over one period

(a) Make a time vector t from 0 to 2ð with enough samples to get smooth lines, Plot sin t.

23
ECE, JIIT NOIDA ODD/EVEN SEMESTER

(b) Use hold on.


(c) Plot cos t using a red dashed line.
(d) Add labels to the plot and create a legend to describe the two lines you have plotted
by using legend.
(e) Use xlim to set the x axis to be from 0 to 2ð and use ylim to set the y axis to be from -
1.4 to 1.4.

6. Plot a circle. Write the function [x, y] = getCircle (center,r) to get the x and y
coordinates of a circle. The circle should be centered at center (2-element vector
containing the x and y values of the center) and have radius r. Return x and y such that
plot(x, y) will plot the circle.

7. Loops and flow control. Make function called loopTest(N) that loops through the
values 1 through N and for each number n it should display „n is divisible by 2‟, „n is
divisible by 3‟, „n is divisible by 2 AND 3‟ or „n is NOT divisible by 2 or 3‟. Use a for
loop, the function mod or rem to figure out if a number is divisible by 2 or 3, and
num2str to convert each number to a string for displaying. You can use any combination
of if, else, and elseif.

8. Linear system of equations. Solve the following system of equations:


3a + 6b + 4c = 1. a + 5b = 2. 7b + 7c = 3

9. Numerical integration. Use trapz or quad. What is the value of :

Compute and display the difference between your numerical answer and the analytical
−5/3
answer: −24 e +9

10. Practice with cells. Usually, cells are most useful for storing strings, because the
length of each string can be unique. a. Make a 3x3 cell where the first column contains
the names: „Joe‟, ‟Sarah‟, and ‟Pat‟, the second column contains their last names:
„Smith‟, „Brown‟, „Jackson‟, and the third column contains their salaries: $30,000,
$150,000, and $120,000. Display the cell using disp.

24
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Experiment 2
Aim: Introduction to continuous time signals.

Theory:

The Signals, which are functions of one or more independent variables, contain
information about the behaviour or nature of some phenomenon. Independent variables
may be time, space etc. depending on type of signals. Some examples are: a speech
signal would be mathematically represented by acoustic pressure as a function of time,
Voltage, current or power as functions of time, a monochromatic picture can be described
as a signal which is mathematically represented by brightness as a function of two spatial
variables,

The purpose of this lab is the introduction of the graphical representation of


elementary as well as Complex Signals. For this Lab, our focus will be on a single (1-D)
independent variable which we call “time”. Depending on time, signals can be classified
into continuous and discrete-time signals used in linear systems. It is important to
emphasize that. A continuous-time signal takes on a value at every point in time, whereas
a discrete-time signal is only defined at integer values of the “time” variable. However,
while discrete-time signals can be easily stored and processed on a computer, it is
impossible to store the values of a continuous-time signal for all points along a segment
of the real line.

How then do we process continuous-time signals? In this lab, we will see that
continuous- time signals may be processed by first approximating them by discrete-time
signals using a process known as sampling. We will see that proper selection of the
spacing between samples is crucial for an efficient and accurate approximation of a
continuous-time signal. Excessively close spacing will lead to too much data with not
much improvement in signal representation, whereas excessively distant spacing will lead
to a poor approximation of the continuous-time signal.

The representation of continuous-time signals on a computer depends on sampling


process. Selection of the sampling interval decides the precision of graphical
representation of CT signal by discrete values.

In MATLAB see plot, subplot commands.

A digital computer cannot store all points of a continuous-time signal since this
would require an infinite amount of memory. It is, however, possible to plot a signal
which looks like a continuous-time signal, by computing the value of the signal at closely
spaced points in time, and then connecting the plotted points with lines. The Matlab plot
function may be used to generate such plots.

25
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Steps for plotting continuous time signals are as follows:


1). Assign the value „dt‟ very small, as per Sampling Theorem.
2). Vary the time„t‟ between two points with an increment of „dt‟.
Use the following sequence of commands in a script file to generate two continuous-time
plots of the signal sin (t/6).

1 % Generate Continuous-time sinusoidal signal


2 t1 = 0:0.1:20,
3 z = sin(t1/6);
4 subplot(3,1,2)
5 plot(t1,z)
6 t2 = 0:1:20;
7 w = sin(t2/6);
8 subplot(3,1,3)
9 plot(t2,w)

IN LAB EXERCISE

Basic CT Signals

Q1. Plot the following continuous-time functions over the specified intervals. Write
single script files for all CT signals with name CTsignals_GroupNo. X.m. Use the plot
and figure command, and be sure to label the time axes.

(a) Unit Impulse function, x1 (t) = δ (t)


(b) Unit Step function, x2(t) = u (t) for t = [-2, 2]
(c) Unit Ramp function, x3(t) = r (t) for t = [-2, 5]
(d) sinusoidal function, x4(t) = 3*sin(2*pi*f*t), where f = 20 Hz for t = - 1 to 1 secs
(e) Exponential function, x5(t) = e-at for t = [-4, 4] for a= 0.5, 1.5. Comment on the effect
of time scaling.
(f) rect(t) for t = [ -2 , 2]
(g) sinc(t) for t = [-1, 10]
Hint: These functions may be computed in Matlab by using a Boolean expression. For
example, if t = -10: 0.1: 10, then y = u (t) may be computed using the Matlab command x
= t > 0.

Q.2 Generate signal x(t) = u(t)-u(t-10).

26
ECE, JIIT NOIDA ODD/EVEN SEMESTER

POST LAB EXERCISE

Q1.Generate the waveform of following signals:

For CT signals, t = is -5 to 5sec. Take appropriate value of sampling interval.

(a) xa(t) = δ(t + 1)


(b) xb(t) = δ(t + 1/2) – δ (t - 1/2)
(c) xc(t) = t u(t)
(d) xd(t) = u (t + 2) – u(t - 3)
(e) xe(t) = r (t +1) – r (t) + r (t - 2)
(f) xf(t) = exp(-t) sin(2πt) + exp(-t/2) cos(5 πt)
(g)
Q2. Sketch the waveform:

b. Using the result of part (a), compute the derivative of v(t), and sketch its waveform.

27
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Experiment 3
Aim: Introduction to Discrete time signals.

Theory: A discrete signal or discrete-time signal is a time series consisting of


a sequence of quantities. In other words, it is a time series that is a function over
a domain of integers.
Unlike a continuous-time signal, a discrete-time signal is not a function of a continuous
argument; however, it may have been obtained by sampling from a continuous-time
signal, and then each value in the sequence is called a sample. When a discrete-time
signal obtained by sampling a sequence corresponds to uniformly spaced times, it has an
associated sampling rate; the sampling rate is not apparent in the data sequence, and so
needs to be associated as a characteristic unit of the system.

Fig.1 Discrete sampled signal.

In Matlab discrete signal represented by dots for this we use command like stem in place
of plot. Start Matlab on your workstation and type the following sequence of commands
in a script file.

1 % Generate discrete-time sinusoidal signal


2 n = 0: 2: 60;
3 y = sin(n/6);
4 subplot(3,1,1)
5 stem(n, y)
This plot shows the discrete-time signal formed by computing the values of the function
sin (n/6) at points which are uniformly spaced at intervals of size 2.
IN LAB EXERCISE

Basic DT Signals

Q1. Plot the following Discrete-time functions over the specified intervals. Write single
script files for all DT signals with name DTsignals_GroupNo_X.m. Use the Stem and
figure command, and be sure to label the time axes.

28
ECE, JIIT NOIDA ODD/EVEN SEMESTER

(h) Unit Impulse function, x1 (n) = δ (n)


(i) Unit Step function, x2(n) = u (n) for n = [-5, 5]
(j) Unit Ramp function, x3(n) = r (n) for n = [-2, 10]
(k) sinusoidal function, x4(n) = 3*sin(2*pi*f*n), where f = 20 Hz for t = - 1 to 1 secs
(l) Exponential function, x5(n) = e-at for n= [-4, 4] for a= 2. Comment on the effect of
time scaling.
(m) x6(n)=rect(n) for n = [ -5 , 5]
(n) x7(n)sinc(n) for t = [-4, 10]
Hint: These functions may be computed in Matlab by using a Boolean expression. For
example, if n = -10: 1: 10, then y = u (n) may be computed using the Matlab command x
= n > 0.

Q.2 Generate signal x(n) = u(n)-u(n-10).

Post lab:

Q.1 For DT signals, n = -5 to 5 samples

a. xa[n] = r[-n]
b. xb[n] = exp(n-1)
c. xc[n] = [n - 1] δ[n - 2]
d. xd[n] = u [n + 1] – 2u[ n] + u [n-1]
e. xe[n] = r [n + 3] – r [n - 3]
f. xf [n] = an cos(2 πn)
Random Signals

The objective of this section is to show how two signals generated using same script file
and “look” similar can be distinguished by computing their average over a large interval.

Q2. Generate two discrete-time signals called sig1 and sig2 of length 1, 000. The samples
of sig1 should be independent, Gaussian random variables with mean 0 and variance 1.
The samples of sig2 should be independent, Gaussian random variables with mean 0.2
and variance 1. Use random or randn to generate these signals, and then plot them in a
same figure. (An alternative name for a Gaussian random variable is a normal random
variable.)

Next form a new signal “ave1(n)” of length 1, 000 such that “ave1(n)” is the average of
the vector “sig1(1:n)” (the expression sig1(1:n) returns a vector containing the first „n‟
elements of “sig1”). Similarly, compute “ave2(n)” as the average of “sig2(1:n)”. Plot the
signals “ave1(n)” and “ave2(n)” versus n on a same plot.

Comment on how the average values changes with n.

29
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Experiment 4
Aim: Introduction to even and odd parts of signal.

Theory: A real-valued sequence xe(n) is called even (symmetric) if

xe(−n) = xe(n)

Similarly, a real-valued sequence xo(n) is called odd (anti-symmetric) if

xo(−n) = −xo(n)

Thus any arbitrary real-valued sequence x(n) can be decomposed into its even and odd
components

x(n) = xe(n) + xo(n)

where the even and odd parts are given by

xe(n) = 1/ 2 [x(n) + x(−n)]

and xo(n) = 1/ 2 [x(n) − x(−n)]

respectively.

Q.1 For given signal x(n)=u(n) obtain its even part xe(n) and xo(n) and plot them. Verify
the results by:

x(n) = xe(n) + xo(n)

Q.2 Let x(n) = u(n) − u(n − 10). Decompose x(n) into even and odd components.

Q.3 Let x(n) = [1 2 4 7 9 4 5]. Decompose x(n) into even and odd components.

Q.4 Let x(n) = [2 1 3 4 2 4 3 1 2]. Decompose x(n) into even and odd components.

Q.5 Let x(t)=t*u(t) for t varies [-2,10]. Obtain its even and odd components.

Q.6 Generate Y(t) such that

30
ECE, JIIT NOIDA ODD/EVEN SEMESTER

t  5,  5  t  2
11  4t ,  2  t  1

Y (t)  
24  9t , 1  t  3
t  6, 3  t  6

Plot Y(t) and also obtain its even and odd part.

31
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Experiment No.5
Aim: Write MATLAB Codes for generating and plotting various combinations of the two
signals and perform time scaling, time shifting, time reversal and multiple
transformations.

Theory: When a signal is processed, they signal undergoes many manipulations


involving the independent variable and the dependent variable. Some of these
manipulations include:
 Shifting the signal in the time domain.

 Folding the signal

 Scaling in the time-domain

A brief introduction of these manipulations is given below.

Shifting
In the case of discrete-time signals, the independent variable is the time, n. A signal x(n)
may be shifted in time, i.e. the signal can be either advanced in the time axis or delayed
in the time axis. The shifted signal is represented by x(n-k), where k is an integer. If „k‟ is
positive, the signal is delayed by k units of time and if k is negative, the time shift results
in an advance of signal by k units of time.
Folding
This operation is done by replacing the independent variable n by –n. This results in
folding of the signal about the origin, i.e. n=0. Folding is also known as the reflection of
the signal about the time origin n=0. Folding of a signal is done while convoluting the
signal with another.
Time scaling
This involves replacing the independent variable n by kn, where k is an integer. This
process is also called as down sampling. If x(n) is the discrete-time signal obtained by
sampling the analogue signal, x(t), then x(n) = x (nT), where T is the sampling period. If
time–scaling is done, then the time-scaled signal, y[n] = x(kn) = x(knT). This implies that
the sampling rate is changed from 1/T to 1/kT.

32
ECE, JIIT NOIDA ODD/EVEN SEMESTER

Implementation
Steps for converting continuous time signal to the discrete time signal are as
follows: 1). Assign the value of sampling time, T .
2). Vary the time integer „n‟ between two integer points with an increment of 1.
3). The discrete version can be obtained as:
y(n) = y(nT).

Useful Commands in MATLAB:


Stem: stem (n, y);
It plots the data sequence Y as stems from the x axis terminated with circles for the data
value. If Y is a matrix then each column is plotted as a separate series.

Subplot : subplot(m ,n, p);


It plots the data sequences by dividing the main figure window In m×n sub- windows
and total m×n subplots can be plotted either in continuous time domain by adding simple
plot in addition with subplot or in discrete time domain by addition of stem.

Q. 1. Write MATLAB Codes for generating and plotting the following combinations of
the two signals over the range, -20< n < 20. .

Let x1[n] = 2sin(2 πn 8)u[n] and x 2 [n] = −4e−(n 6)2


(a) x[n] = x1[n]x2 [n]
(b) x[n] = 4x1[n]+2x2[n]
(c ) x[n] =x1[2n]x2[3n]
(d ) x[n] = x1[2n] /x2[−n]
(e ) x[n] = 3x1[n / 2] + 2x2 [n / 3]

2. Write MATLAB Codes for generating the following Sequences


4 n  6

X [ n]   n  6  n3
 2/n 3 n

Sketch x [-n], x [3-n], x[2n] and x[n/2].

33
ECE, JIIT NOIDA ODD/EVEN SEMESTER

3. Generate x (t) & sketch each of the following signals derived from x (t) :

i. x(3t)
ii x(3t + 2)
iii x(2 −t)

Post Lab Exercise


Q1. Generate this signal:

Q2. Generate x [n] & sketch each of the following signals derived from x [n]:

a. x [2n]
b. x [3n – 1]
c. x [3 - n]

34
ECE, JIIT NOIDA ODD SEMESTER

Q3. Plot the function defined by

0 , t  2
4  2t ,  2  t  0

X (t )  4  3t , 0  t  4
16  2t , 4  t  8

2, t 8
Then plot the transformations 3x(t +1), (1/2) x(4t), -2x((t-1)/2)

35
ECE, JIIT NOIDA ODD SEMESTER

Experiment – 6
Aim: Write MATLAB codes for finding the Signal Energy or power of signals.

Theory: Power and Energy content of a signal is often calculated in signal processing for
communication applications. For any signal in discrete form, power and energy can be calculated
using the following equations.

Energy

The energy of a continuous-time signal x(t) is defined as

The energy is finite only if the above sum converges to a finite value. This implies that the signal
is “squarely-summable”. Such a signal is called finite energy signal.

Power:

Power is defined as the amount of energy consumed per unit time. This quantity is useful if the
energy of the signal goes to infinity or the signal is “not-squarely-summable”.

36
ECE, JIIT NOIDA ODD SEMESTER

Classification of Signals:

A signal can be classified based on its power or energy content. Signals having finite energy are
energy signals. Power signals have finite and non-zero power.

 Energy Signal:

A finite energy signal will have zero TOTAL power. Let‟s investigate this statement in detail.
When the energy is finite, the total power will be zero. Check out the denominator in the
equation for calculating the total power. When the limit N→∞N→∞, the energy dilutes to zero
over the infinite duration and hence the total power becomes zero.
 Power Signal:

Signals whose total power is finite and non-zero. The energy of the power signal will be infinite.
Example: Periodic sequences like sinusoid. A sinusoidal signal has finite, non-zero power but
infinite energy.A signal cannot be both an energy signal and a power signal.

 Neither an Energy signal nor a Power signal:

Signals can also be a cat on the wall – neither an energy signal nor a power signal. Consider a
signal of increasing amplitude defined by

x(n)= n

For such a signal, both the energy and power will be infinite. Thus, it cannot be classified either
as an energy signal or as a power signal.

EXERCISE:

Q.1 Categorize signal as Energy or Power signal and also compute the signal energy or power.
 t, 0  t  1

x(t )  2  t , 1  t  2
a)
0, otherwise

n, 0  n  5

b) x[n]  10  n, 5  n  10
0,
 otherwise

37
ECE, JIIT NOIDA ODD SEMESTER

(c) x(t )  5cos( t )  sin(5 t ),   t 

5cos( t),  1  t  1
(d) x(t )  
0, otherwise

cos( t ),  0.5  t  0.5


(e) x(t)  
0, otherwise

sin( n),  4  n  4
(f) x[n]  
0, otherwise

cos( n), n  0
(g) x[n]  
0, otherwise.

38
ECE, JIIT NOIDA ODD SEMESTER

Experiment – 7

Aim: To calculate the convolution sum of two discrete time signals.

Theory:

Convolution Sum: Convolution of DT Signals

The convolution sum of two DT signals is defined by


f 1 [ n]  f 2 [ n ]   f [k ] f
k  
1 2 [n  k ]
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 of scaled and time -
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.

Thus, the output of an LTI system, y [n] in response to an input, x[n] is given by convolution
sum of impulse response of the system, h [n] and input to the system, x[n].

If one signal has M samples and other has N samples then convolution of these two signals will
have of M+N-1 samples.

Finding Convolution Sum

39
ECE, JIIT NOIDA ODD SEMESTER

Step 1: Define/Sketch x [k] and h [k].


Step 2: The impulse response, h [k] time-reversed or folded to obtain h [-k].
Step 3: Then h [-k] shifted by n to form h [n – k] = h [-(k- n)] which is a function of k with
parameter n. Begin with shift n large and negative, i.e., shift h [-k] to the far left on the time axis.
Step 4: The signal x [k] and h [n – k] are multiplied together for all values of k with n fixed at
some value/range.
Step 5: The product x [k] h [n – k] is summed over all k to produce a single output value y [n].
Step 6: For Calculating the response of the system over all instants of time, repeat steps 3 to 5 till
response at all time instants (n = -∞ to ∞) is obtained.

IN LAB EXERCISE:

Q1. Consider the continuous-time signals

f1[n]  [n], f 2[n]  rect [n], f 3 (t )  [u[n]  u[n  5]]


Write a MATLAB program to perform and verify the continuous-time convolution
commutativity, distributivity and associativity properties (Use conv):

f 1 [ n ]  f 2 [ n ]  f 2 [ n ]  f1 [ n ]
f1[n]  ( f 2 [n]  f 3 [n])  f1[n]  f 2 [n]  f1[n]  f 3 [n]
f1[n]  ( f 2 [n]  f 3 [n])  ( f1[n]  f 2 [n])  f 3 [n]
Q2. Write a MATLAB program to perform the Convolution. Plot the results obtained and
comment on the convolution signal durations. Verify the results by using the MATLAB function
conv.

a) x[n] = [-2 0 1 -1 3] and h[n]= [1 2 0 -1]

b) x[n] = u[n] and h[n]= e-an u[n].

c) x[n]  cos( 2 n)u[n], h[n]  (1) n u[n  1]

POST LAB EXERCISE:


n
 1
1. Consider two LTI systems with the unit sample responses h1[n ]     u[n ]
 2
and h2 [n]  u[n]  u[n  5] .
These two systems are cascaded as shown in fig. Let x[n] = δ[n].

40
ECE, JIIT NOIDA ODD SEMESTER

a. Compute y[n] by first computing w[n]  x[n]  h 1[n] and then computing y[n]  w[n]  h 2 [n] ;
that is y[n]  [ x[n]  h1[n]] h2 [n].
b. Now, find y[n] by first convolving h1[n] and h2[n] to obtain g[n]  h1[n]  h 2 [n] and then
convolving x[n] with g[n] to obtain y[n]  x[n]  [h1[n]  h 2 [n]].

2. Write a function to calculate convolution sum of two DT sequences,


0 , n  1 
 
x[n ]  a n (u[n  2]  u[n  4]) h[n ]   n ,  1  n  4  .
2

 
3 , 4  n  6
0 , n  6 
Verify your answer.

41
ECE, JIIT NOIDA ODD SEMESTER

Experiment -8
Aim: To calculate the convolution integral of two continuous - time signals.

Theory:

Convolution Integral: Convolution of CT Signals

The convolution integral of two CT signals is defined by


f1 (t )  f 2 (t )   f1 () f 2 (t  )d


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.

Thus, the output of an LTI system, y (t) in response to an input, x (t) is given by convolution
integral of impulse response of the system, h (t) and input to the system, x (t).

If one signal has duration of M seconds and other has N seconds then convolution of these two
signals will have duration of M+N seconds.

Finding Convolution Integral

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 3 to 5 till
response at all time instants (t = -∞ to ∞) is obtained.

Symbolic Math Toolbox

42
ECE, JIIT NOIDA ODD SEMESTER

The Symbolic Math Toolbox combines the symbolic mathematics and variable-precision
arithmetic capabilities of the Maple symbolic engine with MATLAB numeric and visualization
capabilities. With the Symbolic Math Toolbox, you can use the MATLAB language and syntax
to perform symbolic computations. The toolbox offers more than 100 symbolic functions for
performing algebraic, calculus, and integral transform operations. The Symbolic Math Toolbox
uses "symbolic objects" produced by the "sym" function.

>> help sym


>> help syms

To see help on Symbolic Math Toolbox functions write help sym/function name in command
window. For example,

>> help sym/dirac


>> help sym/heaviside
>> help sym/int

Finding Convolution Integral in MATLAB using 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- τ) with respect to
τ to produce output, y (t) (Recall pretty, simplify, collect and subs).
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.

IN LAB EXERCISE:

Q1. Consider the continuous-time signals

f1(t )  (t ), f 2 (t )  tri(t ), f3 (t )  [u(t )  u(t  5)]

Write a MATLAB program to perform and verify the continuous-time convolution


commutativity, distributivity and associativity properties (Use conv):

f1 (t )  f 2 (t )  f 2 (t )  f1 (t )
f1 (t )  ( f 2 (t )  f3 (t ))  f1 (t )  f 2 (t )  f1 (t )  f 3 (t )
f1 (t )  ( f 2 (t )  f3 (t ))  ( f1 (t )  f 2 (t ))  f 3 (t )

43
ECE, JIIT NOIDA ODD SEMESTER

Q2. Using Symbolics, generate one CT square signal and a unit impulse signal. Sketch and
evaluate the convolution integral of these two signals and observe the result. Verify your answer
using conv.
Q3. Using Symbolics, generate a square and a triangular CT signals. Sketch and evaluate the
convolution integral of these signals. Verify your answer using conv.

Q4. The impulse response of given system is h(t )  e t u(t ) . Use Symbolics, to determine the
output, y (t) due to input, x (t) = u (t) – u (t -1). Sketch output. Verify your answer using conv.

POST LAB EXERCISE:

Q1. Compute the convolution integral y(t )  x(t )  h(t ) of the following pairs of signals:

3t
a. x(t )  e u(t ), h(t )  u(t  3)

b. x(t)and h(t) depicted below:

Q2. Consider the series RC circuit and assume that the circuit‟s time constant RC =1s. The
impulse response of this circuit is h(t )  e t u(t ) . Use convolution to determine the voltage across
capacitor, y (t) due to input voltage x (t) = u (t) – u (t -2).

44
ECE, JIIT NOIDA ODD SEMESTER

Experiment - 9
Aim: Realization of LTI system and verify it.

Theory: Linear time-invariant (LTI) systems are systems that are both linear and time-invariant.
Let x1(t) and x2(t) be any two signals. Suppose that the output of a system to x1(t) is y1(t) and the
output of the system to x2(t) is y2(t).

If this always implies that the output of the system to

α1*x1(t) + α2*x2(t) = α1*y1(t) + α2*y2(t),

then the system is linear and the superposition principle is said to hold.

A system is said to be time invariant if when y(t) is the output that corresponds to x(t), then for
any τ , y(t − τ ) is the output that corresponds to x(t − τ ).

Input X(t) Output Y(t)


h(t)

Input X(t- τ) h(t) Output Y(t- τ)

Then if input x(t) is delayed by time τ then output is also delayed by same time τ.

To realize the time invariant property use Syms toolbox used in earlier experiment.

Q.1 Check whether the system is LTI or not. In each of the given example y(t) is an output of
system and x(t) is an input of system.

a) y (t )  sin( x(t ))
b) y (t )  log( x(t ))
c) y (t )  x(t ) (h int :use x(t )  t and x1(t )  tau for linearity property)
d) y(t)  x(t)

Q.2 Determine and sketch the overall response h(n) of the system.

45
ECE, JIIT NOIDA ODD SEMESTER

Where, h1(n)   (n), h2(n)  u(n)  u(n  2) and h3(n)   (n  1)

Q.3 A continuous LTI system is characterised by the impulse response, h(t) where

h(t) = u(t+2)-u(t-2). Determine the response y (t) of the system for input x(t).

X (t )   (t  2)   (t  1)   (t  1) .


Hint: Use convolution integral. (i.e. y (t )   x(t )h(t   )d )


46
ECE, JIIT NOIDA ODD SEMESTER

Experiment - 10
Aim: Determine frequency domain representation of CT and DT periodic signals.

Theory: Fourier analysis is a family of mathematical techniques, all based on decomposing


signals into sinusoids. The discrete Fourier transform (DFT) is the family member used with
digitized signals (discrete-time signal). A signal can be either continuous or discrete, and it can
be either periodic or aperiodic. The combination of these two features generates the four
categories, described below.

Periodic-Continuous: Here the examples include: sine waves, square waves, and any waveform
that repeats itself in a regular pattern from negative to positive infinity. This version of the
Fourier transform is called the Fourier series.

Aperiodic-Continuous: This includes, for example, decaying exponentials and the Gaussian
curve. These signals extend to both positive and negative infinity without repeating in a periodic
pattern. The Fourier Transform for this type of signal is simply called the Fourier Transform.

Aperiodic-Discrete: These signals are only defined at discrete points between positive and
negative infinity, and do not repeat themselves in a periodic fashion. This type of Fourier
transform is called the Discrete Time Fourier Transform.

Periodic-Discrete: These are discrete signals that repeat themselves in a periodic fashion from
negative to positive infinity. This class of Fourier Transform is sometimes called the Discrete
Time Fourier Series.

Discrete Fourier Transform (DFT): It is discretized version of DTFT in frequency domain.


The fast algorithm to evaluate DFT is Fast Fourier Transform (FFT).

In Lab Exercise:
1. Use the definition of the CTFS to determine the time –signals represented by the following FS
coefficient.

2. Determine the Fourier series representations of the following signals and Plot the magnitude
and phase of these coefficients:

47
ECE, JIIT NOIDA ODD SEMESTER

3. Determine the time signals represented by following DTFS coefficient.

5 7
a k  1  cos( k )  j sin( k)
9 27
Verify your answer.

Post Lab Exercise:

1. Use the defining equation for the DTFS coefficients to evaluate the FS representation of
discrete time signal.
x[n]  1  cos(3n / 12)  sin(2n / 36)

Sketch the magnitude and phase spectra. Verify answer using „fft‟.

2. Determine the Fourier series representations of the following signals and Plot the
magnitude and phase of these coefficients:

48
ECE, JIIT NOIDA ODD SEMESTER

Experiment - 11
Aim: Determine frequency domain representation of CT and DT aperiodic signals.
Theory: Fourier analysis is a family of mathematical techniques, all based on
decomposing signals into sinusoids. The discrete Fourier transform (DFT) is the family member
used with digitized signals (discrete-time signal). A signal can be either continuous or discrete,
and it can be either periodic or aperiodic. The combination of these two features generates the
four categories, described below.
Periodic-Continuous: Here the examples include: sine waves, square waves, and any waveform
that repeats itself in a regular pattern from negative to positive infinity. This version of the
Fourier transform is called the Fourier series.
Aperiodic-Continuous: This includes, for example, decaying exponentials and the Gaussian
curve. These signals extend to both positive and negative infinity without repeating in a
periodic pattern. The Fourier Transform for this type of signal is simply called the Fourier
Transform.
Aperiodic-Discrete: These signals are only defined at discrete points between positive and
negative infinity, and do not repeat themselves in a periodic fashion. This type of Fourier
transform is called the Discrete Time Fourier Transform.
Periodic-Discrete: These are discrete signals that repeat themselves in a periodic fashion from
negative to positive infinity. This class of Fourier Transform is sometimes called the Discrete Time
Fourier Series.
Discrete Fourier Transform (DFT): It is discretized version of DTFT in frequency
domain. The fast algorithm to evaluate DFT is Fast Fourier Transform (FFT).
In Lab Exercise:
1. Calculate CTFT of signal, x (t) = e-2│ t│cos 5t. Plot magnitude and phase spectra.
Verify your answer.
2.Calculate DTFT of signal, x[n]. Plot magnitude and phase spectra.Verify your answer.
n
1
x[n]    u[ n  2]
 3

49
ECE, JIIT NOIDA ODD SEMESTER

Post Lab Exercise:

1. Determine CTFT of following signals:

2. Determine DTFT of signal, x[n] = ((1/3) n cos (3n)) u [n + 2].

50
ECE, JIIT NOIDA ODD SEMESTER

Experiment-12

Aim: Write your own MATLAB function to compute DFT (Discrete Fourier
Transform) and IDFT (Inverse Discrete Fourier Transform) for the spectral analysis
of signals.

Theory:
We know that aperiodic finite energy signals have continuous spectra (DTFT).

X(ω) =

In case of a finite length sequence x(n), 0≤n≤L-1., Then only L


values of X(ω) over its period, called the frequency samples, are sufficient to determine
x(n) and hence X(ω). This leads to the concept of discrete Fourier transform (DFT) which
is obtained by periodic sampling of X () (DTFT).

We often compute a higher point (N point) DFT where N > L. This is because padding
the sequence x(n) with N-L zeros and computing an N point DFT results in a “better
display” of the Fourier transform X(ω).

To summarize, the formulas are (for causal sequence)

N 1 j 2kn L 1 j 2kn


 
N N

X (k)   x(n)e   x(n)e (DFT), k  0, 1... N  1


n 0 n 0

N 1 j 2kn
N

x(n) 
1
N
 X (k )e (IDFT ), n  0, 1,... N  1
k 0

51
ECE, JIIT NOIDA ODD SEMESTER

General DFT matrix equation is.

X=WN x DFT equation

1
X= WN* X IDFT equation
N

Where WN=e-j2л/N

x=[x(0) x(1) …… x(N-1) ]T

X=[X(0) X(1) …… X(N-1)]T

In lab Exercise:
Write your own MATLAB function to compute DFT (Discrete Fourier Transform) and IDFT
(Inverse Discrete Fourier Transform) for the spectral analysis of signals.

Post Lab Exercise:

Q 1. Find the DFT-transform of the following signals x(n)={1,2,3,2}

Q 2. Find the IDFT of X(K)={4,2,0,4}

Q3. Find the DFT-transform of the following signals

x(n)={1,1,0,0,0,0,0,0}

Q 4. Find the IDFT of X(K)={1,0,1,0}

52
ECE, JIIT NOIDA ODD SEMESTER

Experiment - 13
Aim: Find out output y (t) of the system where input is x (t) and impulse response is h (t) using
Laplace Transform. Also, find the ROC of the transform.

Theory: The Laplace transform is closely related to the Fourier transform and the z-
transform. An important difference between the Fourier transform and the Laplace transform is
that the Fourier transform uses a summation of waves of positive and negative frequencies,
while the Laplace transform employs damped waves through the use of an additional factor e-σ
Where σ is a positive number. The Fourier transform and the Laplace transform are
operations that convert the time domain function f(t) to the frequency domain function F(jω) and
F(s) respectively.
The relation between the output signal y(t) and the input signal x(t) in a RLC circuit is a linear
differential equation of the form given by
N M
∑ a k d y(t)/dt = ∑ b k dkx(t)/dtk
k k

k= 1 k=0
The Laplace Transform gives the total solution to the differential equation and
corresponding initial and final value problem.
Laplace transform is an important and powerful tool in system analysis and design. This transform
is widely used for describing continuous circuits and systems, including automatic control
systems.
Definition:
For periodic or non-periodic time functions f(t), which is zero for t<=0 and defined for t>0, the
Laplace transform of f(t), denoted as L{f(t)} is defined by

53
ECE, JIIT NOIDA ODD SEMESTER

Putting
s = σ+jω, we have

and Inverse Laplace Transform

54
ECE, JIIT NOIDA ODD SEMESTER

Region of Convergence (ROC):


For the existence of the Laplace Transform, the integral

must converge. This limits the variable s = σ + j ω to a part of complex plane


called the Region of Convergence.
Useful Commands in MATLAB:

L = laplace (F) is the Laplace transform of the scalar symbol F with default independent variable
t. The default return is a function of s. The Laplace transform is applied to a function of t and
returns a function of s.
Inverse Laplace transform can be evaluated using ( ilaplace )command.

IN LAB EXERCISE:
1. Write a function to sketch and calculate convolution integral of two CT signals,

x(t) = t*u(-t) h(t) = e2t u(t) Verify your answer.

2. Consider a signal y (t) which is related to two signals x1(t) and x2(t)
2t 3t
by y(t )  x1 (t  2)  x 2 (2t  3) where x1 (t )  e u(t ) and x 2 (t )  e u(t )
Determine Y(s) and y (t). Verify your answer.
POST LAB EXERCISE:
1. Use the MATLAB command to determine the poles and zeros of following systems and also
evaluate inverse Lapalce transform of function given below.
2
a).H ( s) 
s  s  s 1
3 2

s 2  8s  1
b) H ( s )  3
2s  8s 2  8s  20

2. Consider an LTI system with input, x(t) and impulse response, h(t).
x(t )  e t u(t ) h(t )  e 2t u(t )

a) Determine the Laplace transform of x(t) and h(t).


b) Determine the Laplace transform Y(s) of the output y (t).
c) From Laplace transform Y(s) of the output y (t), determine y (t).
d) Verify your result in part (c) by explicitly convolving x (t) and h (t).

55
ECE, JIIT NOIDA ODD SEMESTER

Experiment - 14
Aim: Find out output y [n] of the system where input is x[n] and impulse response is h[n] using Z-
Transform. Also, find the ROC of the transform. Verify answer using MATLAB commands
„ztrans‟ and „iztrans‟. Check stability of the system using MATLAB

Theory: The z-transform is an important tool in the analysis of discrete-time signals and systems.
It defines the relationship between the time domain signal, x(n) , and the z-domain signal, X(z).
The z-transform may be used to solve constant coefficient difference equations, evaluate the
response of a linear time-invariant system to a given input, and design linear filters. A recursive filter
is described by a difference equation:

Where x[n] and y[n] is the input and output signal, respectively. An obvious use of this
equation is to describe how a programmer would implement the filter. An equally
important aspect is that it represents a mathematical relationship between the input and
output that must be continually satisfied. Just as continuous systems are controlled by
differential equations, recursive discrete systems operate in accordance with this
difference equation. From this relationship we can derive the key characteristics of the
system: the impulse response, step response, frequency response, and pole-zero plot, etc.

We start the analysis by taking the z-transform of the both sides of above recursive equation.
In other words, we want to see what this controlling relationship looks like in the z-domain. With
a fair amount of algebra, we can separate the relation into: Y[z] / X[z], that is, the z-domain
representation of the output signal divided by the z-domain representation of the input signal.
Just as

with the Laplace transform, this is called the system's transfer function, and designate it by H(z) .
Here is what we find:
An important feature of the z-domain is that the transfer function can be expressed as poles
and zeros. This provides the second general form of the z-domain:
Each of the poles (p1, p2, p3,…) and zeros (z1, z2, z3…) is a complex number. By
checking the locations of poles on z-plane, the stability of the system can be determined. If all the
poles lie inside the unit circle, the system is said to be stable.
Useful Commands in MATLAB:
ztrans - Z-transform
iztrans-Inverse Z-transform.
zplane - Z-plane zero-pole plot.

56
ECE, JIIT NOIDA ODD SEMESTER

conv - Convolution and polynomial multiplication.

IN LAB EXERCISE:
1. Determine the z-transform for each of the following sequences. Sketch pole-zero plot and
indicate the region of convergence. Indicate whether or not the Fourier transform of the
sequence exists.

2. Consider the LTI system with input


1,0  n  N  1 
a n , n  0
x[n]   and impulse response h[n]   .
0, otherwise 
0, n  0

(a) Determine the z-transform of x[n] and h[n].


(b) Using the convolution property, determine the z- transform Y (z) of the output y[n].
(c) From z- transform Y (z) of the output y[n], détermine y[n].
(d) Verify your result in part (c) by explicitly convolving x[n] and h[n].

POST LAB EXERCISE:


1. Use the Matlab Command to obtain a pole-zero plot for the following systems and also evaluate
inverse z transform of given functions.

1  z 2  3z 3
H ( z) 
2  z 1  12 z 2  14 z 3

2.For each of the following z-transforms, determine the inverse z-transform

57
ECE, JIIT NOIDA ODD SEMESTER

Experiment – 15

Aim: Introduction to SIMULINK and to realize systems described by differential and


difference equations.

Theory:

This lab introduces powerful numerical simulation software, MATLAB and its graphical user
interface (GUI), Simulink. This software is used for solving the modeling equations and
obtaining the response of a system to different inputs. The software is run on digital
computers. Both linear and nonlinear differential equations can be solved numerically with
high precision and speed, allowing system responses to be calculated and displayed for many
input functions. To provide an interface between a system‟s modeling equations and the
digital computer, block diagrams drawn from the system‟s differential equations are used. A
block diagram is an interconnection of blocks representing basic mathematical operations in
such a way that the overall diagram is equivalent to the system‟s mathematical model. The
lines interconnecting the blocks represent the variables describing the system behaviour.
These may be inputs, outputs, state variables, or other related variables. The blocks represent
operations or functions that use one or more of these variables to calculate other variables.
Block diagrams can represent modelling equations in both input-output and state variable
form.

We use MATLAB with its companion package Simulink, which provides a graphical user
interface (GUI) for building system models and executing the simulation. These models are
constructed by drawing block diagrams representing the algebraic and differential equations
that describe the system behaviour. The operations that we generally use in block diagrams
are summation, gain, and integration. Other blocks, including nonlinear elements such as
multiplication, square root, exponential, logarithmic, and other functions, are available.
Provisions are also included for supplying input functions, using a signal generator block,
constants etc and for displaying results, using a scope block.

An important feature of a numerical simulation is the ease with which parameters can be
varied and the results observed directly. MATLAB is used in a supporting role to initialize
parameter values and to produce plots of the system response. Also MATLAB is used for
multiple runs for varying system parameter-s. Only a small subset of the functions of
MATLAB will be considered during these labs.

SIMULINK

Simulink provides access to an extensive set of blocks that accomplish a wide range of
functions useful for the simulation and analysis of dynamic systems. The blocks are grouped
into libraries, by general classes of functions.

• Mathematical functions such as summers and gains are in the Math library.

58
ECE, JIIT NOIDA ODD SEMESTER

• Integrators are in the Continuous library.

• Constants, common input functions, and clock can all be found in the Sources library.

• Scope, To Workspace blocks can be found in the Sinks library.

Simulink is a graphical interface that allows the user to create programs that are actually run
in MATLAB. When these programs run, they create arrays of the variables defined in
Simulink that can be made available to MATLAB for analysis and/or plotting. The variables
to be used in MATLAB must be identified by Simulink using a To Workspace block, which
is found in the Sinks library. (When using this block, open its dialog box and specify that the
save format should be Matrix, rather than the default, which is called Structure.) The Sinks
library also contains a Scope, which allows variables to be displayed as the simulated system
responds to an input. This is most useful when studying responses to repetitive inputs.

Simulink uses blocks to write a program. Blocks are arranged in various libraries according
to their functions. Properties of the blocks and the values can be changed in the associated
dialog boxes. Some of the blocks are given below.

SUM (Math library)

A dialog box obtained by double-clicking on the SUM block performs the configuration of
the SUM block, allowing any number of inputs and the sign of each. The sum block can be
represented in two ways in Simulink, by a circle or by a rectangle. Both choices are shown

X1

X1

X2 X2

X3
X3

Two Simulink blocks for a summer representing y = x 1+ x2 – x3

GAIN (Math library)

A gain block is shown by a triangular symbol, with the gain expression written inside if it
will fit. If not, the symbol - k - is used. The value used in each gain block is established in a
dialog box that appears if the user double-clicks on its block.

Simulink block for a gain of K.

59
ECE, JIIT NOIDA ODD SEMESTER

INTEGRATOR (Continuous library)

The block for an integrator as shown below looks unusual. The quantity 1/s comes from the
Laplace transform expression for integration. When double-clicked on the symbol for an
integrator, a dialog box appears allowing the initial condition for that integrator to be
specified. It may be implicit, and not shown on the block, as in Figure (a). Alternatively, a
second input to the block can be displayed to supply the initial condition explicitly, as in part
(b) of Figure 3. Initial conditions may be specific numerical values, literal variables, or
algebraic expressions.

Two forms of the Simulink block for an integrator.

(a) Implicit initial condition. (b) Explicit initial condition.

CONSTANTS (Source library)

Constants are created by the Constant block, which closely resembles Figure 4. Double-
clicking on the symbol opens a dialog box to establish the constant‟s value. It can be a
number or an algebraic expression using constants whose values are defined in the workspace
and are therefore known to MATLAB.

A constant block

STEP (Source library)

A Simulink block is provided for a Step input, a signal that changes (usually from zero) to a
specified new, constant level at a specified time. These levels and time can be specified
through the dialog box, obtained by double-clicking on the Step block.

A step block

60
ECE, JIIT NOIDA ODD SEMESTER

SIGNAL GENERATOR (Source library)

One source of repetitive signals in Simulink is called the Signal Generator. Double-clicking
on the Signal Generator block opens a dialog box, where a sine wave, a square wave, a ramp
(sawtooth), or a random waveform can be chosen. In addition, the amplitude and frequency
of the signal may be specified. The signals produced have a mean value of zero. The
repetition frequency can be given in Hertz (Hz), which is the same as cycles per second, or in
radians/second.

A signal generator block

SCOPE (Sinks library)

The system response can be examined graphically, as the simulation runs, using the Scope
block in the sinks library. This name is derived from the electronic instrument, oscilloscope,
which performs a similar function with electronic signals. Any of the variables in a Simulink
diagram can be connected to the Scope block, and when the simulation is started, that
variable is displayed. It is possible to include several Scope blocks. Also it is possible to
display several signals in the same scope block using a MTJX block in the signals & systems
library. The Scope normally chooses its scales automatically to best display the data.

A scope block with MUX block

Two additional blocks will be needed if we wish to use MATLAB to plot the responses
versus time. These are the Clock and the To Workspace blocks.

CLOCK (Sources library)

The clock produces the variable “time” that is associated with the integrators as MATLAB
calculates a numerical (digital) solution to a model of a continuous system. The result is a
string of sample values of each of the output variables. These samples are not necessarily at
uniform time increments, so it is necessary to have the variable “time” that contains the time
corresponding to each sample point. Then MATLAB can make plots versus “time.” The
clock output could be given any arbitrary name; we use “t” in most of the cases.

A clock block
61
ECE, JIIT NOIDA ODD SEMESTER

To Workspace (Sinks library)

The To Workspace block is used to return the results of a simulation to the MATLAB
workspace, where they can be analyzed and/or plotted. Any variable in a Simulink diagram
can be connected to a ToWorkspace block. In our exercises, all of the state variables and the
input variables are usually returned to the workspace. In addition, the result of any output
equation that may be simulated would usually be sent to the workspace. In the block
parameters drop down window, change the save format to „array‟.

A To Workspace block

In the Simulink diagram, the appearance of a block can be changed by changing the
foreground or background colours, or by drop shadow or other options available in the format
drop down menu. The available options can be reached in the Simulink window by
highlighting the block, then clicking the right mouse button. The Show Drop Shadow option
is on the format drop-down menu.

Simulink provides scores of other blocks with different functions.

You are encouraged to browse the Simulink libraries and consult the online Help facility
provided with MATLAB.

GENERAL INSTRUCTIONS FOR WRITING A SIMULINK PROGRAM

To create a simulation in Simulink, follow the steps:

• Start MATLAB.

• Start Simulink.

• Open the libraries that contain the blocks you will need. These usually will include the
Sources, Sinks, Math and Continuous libraries, and possibly others.

• Open a new Simulink window.

• Drag the needed blocks from their library folders to that window. The Math library,
for example, contains the Gain and Sum blocks.

• Arrange these blocks in an orderly way corresponding to the equations to be solved.

• Interconnect the blocks by dragging the cursor from the output of one block to the
input of another block. Interconnecting branches can be made by right-clicking on an
existing branch.

• Double-click on any block having parameters that must be established, and set these
parameters. For example, the gain of all Gain blocks must be set. The number and
62
ECE, JIIT NOIDA ODD SEMESTER

signs of the inputs to a Sum block must be established. The parameters of any source
blocks should also be set in this way.

• It is necessary to specify a stop time for the solution. This is done by clicking on the
Simulation > Parameters entry on the Simulink toolbar.

At the Simulation > Parameters entry, several parameters can be selected in this dialog box,
but the default values of all of them should be adequate for almost all of the exercises. If the
response before time zero is needed, it can be obtained by setting the Start time to a negative
value. It may be necessary in some problems to reduce the maximum integration step size
used by the numerical algorithm. If the plots of the results of a simulation appear “choppy” or
composed of straight-line segments when they should be smooth, reducing the max step size
permitted can solve this problem.

IN LAB EXERCISE:

1. Generate the continuous – time sinusoidal signal with amplitude 2, fundamental


frequency 200 Hz and phase π/2.
2. Generate a rectangular wave of amplitude 3 volts, fundamental frequency 25 Hz.
3. Determine the frequency response, step response of systems given below:
2
a ). H ( s ) 
s  s  s1
3 2

s 2  8s  1
b) H ( s ) 
2s 3  8s 2  8s  20

4. Plot the magnitude and phase response of the given systems.


1  z 2  3 z  3
a.H ( z ) 
2  z 1  12 z  2  14 z  3

5. Realize system for transfer functions given in 4 and 5.

POST LAB EXERCISE:


1. Generate the continuous – time sinusoidal signal with amplitude 5, fundamental
frequency 20 Hz and phase π/6.
2. Generate a square wave of amplitude 2 volts, fundamental frequency 10 Hz and duty
cycle 0.5.
3. Using fft block, determine the DTFS coefficients of the signal for time period, N =
24. Sketch the magnitude & phase spectra.
 3
x[n]  1  sin( n  )
12 8

4. Using ifft, determine the time signals represented by following DTFS coefficient.
5 7
a k  1  cos( k )  j sin( k )
9 27
5. Construct this model and verify whether this system is linear or not.

63
ECE, JIIT NOIDA ODD SEMESTER

64

You might also like