100% found this document useful (1 vote)
336 views

Signals & Systems Lab Manual

This lab manual introduces students to MATLAB through a series of experiments. The first experiment focuses on getting familiar with basic MATLAB functionality like defining variables, functions, vectors and matrices. It also covers arithmetic operators and mathematical functions. The goal is to help students get comfortable with MATLAB's development environment and programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
336 views

Signals & Systems Lab Manual

This lab manual introduces students to MATLAB through a series of experiments. The first experiment focuses on getting familiar with basic MATLAB functionality like defining variables, functions, vectors and matrices. It also covers arithmetic operators and mathematical functions. The goal is to help students get comfortable with MATLAB's development environment and programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 63

LAB MANUAL FOR

SIGNALS AND SYSTEMS LAB

JUNE 2013-14

G.L.BAJAJ INSTUTUTE OF MANAGEMENT AND


TECHNOLOGY, GREATER NOIDA [UP]
Department of Electronics and Communication
CONTENTS
EXPT. Name of the Objective Expected Page
NO. Expt. Outcome No.
Introduction to 1. To define and use To get
01 MATLAB variables and functions familiarized
in MATLAB. with
2. To define and use MATLAB, its
vectors and Matrices in functions and
MATLAB. basic
3. To study various programming
MATLAB arithmetic skills.
operators and
mathematical functions.
4. To create and use m-
files.
Basic plotting of 1. To study various To understand
02 signals MATLAB commands generation of
for creating two and basic CT and
three-dimensional plots. DT signals
2. Write a MATLAB using
program to plot the MATLAB and
following Continuous learn
time and discrete time MATLAB
signals. commands for
i) Step Function creating 2-D
ii) Impulse Function and 3-D plots
iii) Exponential
Function
iv) Ramp Function
v) Sine Function
Time and 1. Write a MATLAB To explore the
03 Amplitude program to perform effect of
Transformations amplitude –scaling, transformation
time-scaling and time of signal
shifting on a given parameters
signal by defining
functions.
Convolution of 1. Write a MATLAB To study and
04 given signals program to obtain linear interpret linear
convolution of the given convolution
CT and DT sequence
using the function conv.
2. Compare and verify the
result obtained with the
expected theoretical
results.
Autocorrelation 1. Write a MATLAB To study and
05 and Cross- program to compute interpret
correlation autocorrelation of a autocorrelation
sequence x(n) and and cross-
verify the property. correlation
2. Write a MATLAB
program to compute
cross-correlation of a
sequence x(n) and y(n)
and verify the property.
Fourier Series 1. To calculate Fourier To be able to:
06 and Gibbs Series coefficients Understand
Phenomenon associated with Square Fourier series
Wave and Triangular expansion of
wave. periodic
2. To sum the first 10 functions,
terms and plot the Observe and
Fourier series as a understand
function of time. Gibbs
3. To sum the first 50 phenomenon
terms and plot the
Fourier Series as a
function of time .
Calculating 1. Calculate Fourier To be able to
07 transforms using Transform of a given calculate
MATLAB signal and plot the Transforms
magnitude and the using
phase spectrum. MATLAB
2. Calculate the Z- commands
transform of a given
signal and plot the poles
and zeros of the Z-
transform
Impulse response 1. Write a MATLAB To be able to
08 and Step program to find the compute, plot
response of a impulse response and and analyze
given system step response of a the impulse
system from its response and
difference equation. step response
2. Compute and plot the of an LTI
sequence of a given system
system to a given input.
Pole-Zero 1. For a given system To be able to:
09 diagram and function write a Plot and
Bode diagram MATLAB program to analyze pole-
plot the poles, zero zero diagram,
configuration and Bode plot and
plot. analyze Bode
2. Analyze the stability of diagram
the given system from
the Bode plot
Transfer function 1. Write a MATLAB To be able to
10 and frequency program to plot the plot and
response of a frequency response of analyze
system the first order system. Magnitude and
2. Also write MATLAB Phase
program to calculate the response
rise time and bandwidth diagram
of same system.
11. Checking 1. Build a system that To be able to
Linearity/Non- amplifies a sine wave test
Linearity of a by a factor of two. linearity/no-
system using 2. Test the linearity of this linearity of the
SIMULINK system using given system
SIMULINK and
understand the
principle of
superposition
EXPERMENTAL NO.-1

AIM: Introduction to MATLAB:

i) To define and use variables and functions in MATLAB.


ii) To define and use vectors and Matrices in MATLAB.
iii) To study various MATLAB arithmetic operators and mathematical
functions.
iv) To create and use m-files.
Introduction:
The purpose of this lab is to familiarize yourself with basic MATLAB
functionality. MAT-LAB is a computational tool consisting essentially of a
command interpreter/compiler for which there is a vast set of libraries and
graphical representation tools, in addition to a nice
user interface. Because of its simplicity and ease of use it is widely used in
industrial and academic environments.
In this lab you will focus on several easy tasks that will make you feel comfortable
with MAT-LAB's development environment and programming language. A more
comprehensive intro-duction/tutorial can be obtained for free from Mathworks, the
makers of MATLAB
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.shtml (in
documentation choose Getting Started ). After gaining some experience you'll
rarely need any tutorials or books, since the available help command and the
ability of searching the electronic documentation is satisfactory for most problems.

Basic of MATLAB:
Whenever you are unsure of the syntax of a command, or want to find how to do
some-thing you can rely on a few helpful commands that can quickly provided
with the needed information. The most basic command we will use is help. Typing:

>> help help;

at the MATLAB prompt we get:

HELP On-line help, display text at command line.

HELP, by itself, lists all primary help topics. Each primary topic corresponds to a
directory name on the MATLABPATH.
"HELP TOPIC" gives help on the specified topic. The topic can be a command
name, a directory name, or a MATLABPATH relative partial pathname (see HELP
PARTIALPATH). If it is a command name, HELP displays information on that
command. If it is a directory name, HELP displays the Table-Of-Contents for the
specified directory. For example, "help general" and "help matlab/general" both list
the Table-Of-Contents for the directory toolbox/matlab/general.

HELP FUN displays the help for the function FUN.

T = HELP('topic') returns the help text in a '\n' separated string.

LOOKFOR XYZ looks for the string XYZ in the first comment line of the HELP
text in all M-files found on the MATLABPATH. For all files in which a match
occurs, LOOKFOR displays the matching lines.

MORE ON causes HELP to pause between screenfuls if the help text runs to
several screens.

In the online help, keywords are capitalized to make them stand out. Always type
commands in lowercase since all command and function names are actually in
lowercase. For tips on creating help for your m-files 'type help.m'.

See also LOOKFOR, WHAT, WHICH, DIR, MORE.

For example, to learn more about the function sum you should type help sum. This
is the general style of help. It not only gives a detailed description of the topic
often including examples, but refers to related topics as well. For example, when
seeking help about the function sum you also learn that there is a function prod that
is somewhat related.

This style of help is displayed on the prompt. As you probably noticed the screen is
cluttered with text and we need to scroll up in order to read the full article. An
arguably better way to get help is to use the HTML version. The command doc
works the same way as help with the difference that it launches a window
displaying the HTML version of the help file. This way is preferable as links to
related commands as well as graphics are included. Typing:

>> doc help;


gives us the HTML version. Typing help without arguments gives us a full list of
topics and toolboxes with short descriptions.

Variables:
Defining variables
As we have seen in previous sections we can type commands and execute them in
the command prompt >>. Now if we type:

We define a variable x and assign the value 5. Notice that we don't need to define
the type (such as string or number) of the variable. MATLAB is able to infer the
type (within reason).

So now when we type:

Clearing variables:

The command:

clears the variable from the workspace. This is useful for example when we want
to reclaim system memory. We can also clear variables when we want to make sure
that any old values are not going to be used by accident.

Built-in variables:
MATLAB includes a number of special variables that are built in the system. For
example, entering pi gives us the value of pi

Other special variables include i and j , that, as you guessed, correspond to the
imaginary unit. It is possible to overwrite special variables. For example, typing pi
= 5 assigns a new value, thus loosing its previous, built-in value. The original
values of the built-in variables can be returned by using the clear statement as
illustrated below:
Scalars, Vectors and Matrices:
MATLAB's simplest mathematical objects are scalars, vectors and matrices. These
are the quantities you are going to manipulate more often, as vectors and matrices
can be used to represent signals, images, among other things. The command
interpreter is highly optimized to perform operations with vectorial quantities. This
is in fact what the name MATrix to LABratory denotes. In this lab session you will
get a first contact with these objects, and will learn more in subsequent lab
sessions.

There are two types of vectors. Row vectors and column vectors. By convention
one typically uses column vectors to represent signals. For displaying purposes we
will use row vectors since they occupy less lines when printed. The simplest way
to create a column vector is by the bracket concatenation operator. We separate the
various values by using a semi-colon.

Typing:
If we want to create a row vector instead we can use spaces or commas as
separators instead:

Operators:
One can see MATLAB as a glorified calculator. In this sense operators are the
special characters that provide MATLAB the calculator functionality. The most
basic operators

are:
The use of most operators is self explanatory but if you need more help in any of
them you can use the help system, e.g. help m times gives:
Elementary functions:
The elementary functions can be found by typing help elfun. The most basic
functions follow.

Elementary math functions.


Trigonometric.

sin - Sine.

sinh - Hyperbolic sine.

asin - Inverse sine.

asinh - Inverse hyperbolic sine.

cos - Cosine.

cosh - Hyperbolic cosine.

acos - Inverse cosine.


acosh - Inverse hyperbolic cosine.

tan - Tangent.

tanh - Hyperbolic tangent.

atan - Inverse tangent.

atan2 - Four quadrant inverse tangent.

atanh - Inverse hyperbolic tangent.

sec - Secant.

sech - Hyperbolic secant.

asec - Inverse secant.

asech - Inverse hyperbolic secant.

csc - Cosecant.

csch - Hyperbolic cosecant.

acsc - Inverse cosecant.

acsch - Inverse hyperbolic cosecant.

cot - Cotangent.

coth - Hyperbolic cotangent.

acot - Inverse cotangent.

acoth - Inverse hyperbolic cotangent.

Exponential.

exp - Exponential.

log - Natural logarithm.

log10 - Common (base 10) logarithm.

log2 - Base 2 logarithm and dissect floating point number.


pow2 - Base 2 power and scale floating point number.

realpow - Power that will error out on complex result.

reallog - Natural logarithm of real number.

Realsqrt - Square root of number greater than or equal to zero.

sqrt - Square root.

nextpow2 - Next higher power of 2.

Complex.

abs - Absolute value.

angle - Phase angle.

complex - Construct complex data from real and imaginary parts.

conj - Complex conjugate.

imag - Complex imaginary part.

real - Complex real part.

unwrap - Unwrap phase angle.

isreal - True for real array.

cplxpair - Sort numbers into complex conjugate pairs.

Rounding and remainder.

fix - Round towards zero.

floor - Round towards minus infinity.

ceil - Round towards plus infinity.

round - Round towards nearest integer.

mod - Modulus (signed remainder after division).

rem - Remainder after division.


sign - Signum.

Remember to use the help command to get more information for any of those
functions.

Flow control:
The for statement:
Repeating statements for an arbitrary number of times is one of the most important
features

of most programming languages. It used to be the case that MATLAB was not able
to repeat statements efficiently but this is not true anymore. Starting with version
6.5 MATLAB includes a JIT-compiler which is responsible for optimizing loops.
The for loop repeats a group of statements for a fixed, predetermined number of
times. A matching end denotes the end of the loop. For example:

The semicolon terminating the inner statement suppresses repeated printing, and
the s after the loop displays the final result. Nested loops are good to be indented
for readability. The MATLAB editor smart-indents nested loops and other
constructs as we type. For example indentation makes the following loop more
readable.

The if statement:
The if statement executes a group of commands depending on the value of a
logical expression. The else and elseif constructs are optional and provide
additional branching. For example
EXPERIMENT NO.-2

AIM: Basic plotting of signals

1. To study various MATLAB commands for creating two and three-


dimensional plots.
2. Write a MATLAB program to plot the following Continuous time and
discrete time signals.
i) Step Function
ii) Impulse Function
iii) Exponential Function
iv) Ramp Function
v) Sine Function
APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PART 1

1. Introduction :
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, Modeling, 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, in a
fraction of the time it would take to write a program in a scalar non interactive
language such as C or Fortran. The name MATLAB stands for matrix laboratory.
Starting MATLAB on Windows platforms, start MATLAB by double-clicking the
MATLAB shortcut icon on your Windows desktop.

Quitting MATLAB: To end your MATLAB session, select File > Exit MATLAB in
the desktop, or type quit in the Command Window. You can run a script file
named finish.m each time MATLAB quits that, for example, executes functions
to save the workspace.

2. MATLAB desktop:

On starting MATLAB the MATLAB desktop appears, containing tools (graphical


user interfaces ) for managing files , variables and applications associated with
MATLAB. It contains :

(i) Command Window and Command History

Command Window : Use the Command Window to enter variables and to run
functions and M-file scripts. Press the up arrow key to recall a statement
previously typed. Edit the statement as needed and then press Enter to run it.

Command History : Statements entered in the Command Window are logged


in the Command History. From the Command History, previously run
statements can be viewed, copied and executed. M-file can be created from
selected statements.

(ii) Current Directory Browser and Search Path : MATLAB file operations use the
current directory and the search path as reference points. Any file required to
run must either be in the current directory or on the search path.

(iii) Workspace Browser and Array Editor :The MATLAB workspace consists of
the set of variables (named arrays) built up during a MATLAB session and
stored in memory. The variables can be added to the workspace by using
functions, running M-files, and loading saved workspaces. To delete variables
from the workspace, select the variables and select Edit > Delete.
Array Editor : Double-click a variable in the Workspace browser, or use open
var variable name, to see it in the Array Editor. Use the Array Editor to view and
edit a visual representation of variables in the workspace.

(iv) Editor/Debugger : Editor/Debugger is used to create and debug M-files,


which are programs 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.

The important commands/ functions are as below :

1. clc (Remove items from workspace, freeing up system memory) clears all
input and output from the Command Window display, giving "clean
screen." After using clc, the scroll bar cannot be used to see the history of
functions, but still the up arrow can be used to recall statements from the
command history.

2. close (Remove specified figure): close deletes the current figure or the
specified figure(s). It optionally returns the status of the close operation.

3. xlabel, ylabel, zlabel (Label x-, y-, and z-axis) : Each axes graphics object
can have one label for the x-, y-, and z-axis. The label appears beneath its
respective axis in a two-dimensional plot and to the side or beneath the axis
in a three-dimensional plot.
xlabel('string') labels the x-axis of the current axes.

ylabel(...) and zlabel(...) label the y-axis and z-axis, respectively, of the
current axes.

4. title( Add title to current axes) : Each axes graphics object can have one
title. The title is located at the top and in the center of the axes.
title('string') outputs the string at the top and in the center of the current
axes.
5. figure (create figure graphics object) : figure creates figure graphics objects.
Figure objects are the individual windows on the screen in which MATLAB
displays graphical output.

6. subplot (Create axes in tiled positions): subplot divides the current figure
into rectangular panes that are numbered row wise. Each pane contains an
axes object. Subsequent plots are output to the current pane.

h = subplot(m,n,p) or subplot(mnp) breaks the figure window into an m-by-


n matrix of small axes, selects the pth axes object for the current plot, and
returns the axes handle. The axes are counted along the top row of the
figure window, then the second row, etc. For example,

subplot(2,1,1), plot(income)

subplot(2,1,2), plot(outgo) plots income on the top half of the window and
outgo on the bottom half.

7. stem (Plot discrete sequence data) : A two-dimensional stem plot displays


data as lines extending from a baseline along the x-axis. A circle (the
default) or other marker whose y-position represents the data value
terminates each stem.
stem(Y) Plots the data sequence Y as stems that extend from equally
spaced and automatically generated values along the x-axis. When Y is a
matrix, stem plots all elements in a row against the same x value.

stem(X,Y) plots X versus the columns of Y. X and Y must be vectors or


matrices of the same size. Additionally, X can be a row or a column vector
and Y a matrix with length(X) rows.

8. bar(Plot bar graph (vertical and horizontal)) : A bar graph displays the
values in a vector or matrix as horizontal or vertical bars.
bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the
bars produced by the elements in each row. The x-axis scale ranges from 1
up to length(Y) when Y is a vector, and 1 to size(Y,1), which is the number of
rows, when Y is a matrix.
barh(...) and h = barh(...) create horizontal bars. Y determines the bar
length. The vector x is a vector defining the y-axis intervals for horizontal
bars.

9. plot ( 2-D line plot) :


plot(Y) Plots the columns of Y versus their index if Y is a real number. If Y is
complex, plot(Y) is equivalent to plot(real(Y),imag(Y)). In all other uses of plot,
the imaginary component is ignored.

plot(X1,Y1,...) Plots all lines defined by Xn versus Yn pairs. If only Xn or Yn is


a matrix, the vector is plotted versus the rows or columns of the matrix,

depending on whether the vector's row or column dimension matches the


matrix. If Xn is a scalar and Yn is a vector, disconnected line objects are
created and plotted as discrete points vertically at Xn.

10.input (Request user input) : The response to the input prompt can be any
MATLAB expression, which is evaluated using the variables in the current
workspace.
user_entry = input('prompt') Displays prompt as a prompt on the
screen, waits for input from the keyboard, and returns the value entered in
user_entry. user_entry = input('prompt', 's') returns the entered string as a
text variable rather than as a variable name or numerical value.

11. zeros (Create array of all zeros) :

B = zeros(n) Returns an n-by-n matrix of zeros. An error message appears if


n is not a scalar.

12. ones (Create array of all ones) :

Y = ones(n) Rreturns an n-by-n matrix of 1s. An error message appears if n is


not a scalar.

13. exp (Exponential) :

Y = exp(X) The exp function is an elementary function that operates


element-wise on arrays. Its domain includes complex numbers.
Y = exp(X) returns the exponential for each element of X.

14. disp (Display text or array) :

disp(X) Displays an array, without printing the array name. If X contains a


text string, the string is displayed. Another way to display an array on the
screen is to type its name, but this prints a leading "X=," which is not always
desirable. Note that disp does not display empty arrays.

15. conv (Convolution and polynomial multiplication) :

w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the


same operation as multiplying the polynomials whose coefficients are the
elements of u and v.

16. xcorr (Cross-correlation) :

c = xcorr(x,y) returns the cross-correlation sequence in a length 2*N-1


vector, where x and y are length N vectors (N>1). If x and y are not the same
length, the shorter vector is zero-padded to the length of the longer vector.

17. filter (1-D digital filter) :

y = filter(b,a,X) filters the data in vector X with the filter described by


numerator coefficient vector b and denominator coefficient vector a. If a(1)
is not equal to 1, filter normalizes the filter coefficients by a(1). If a(1)
equals 0, filter returns an error.

18. poly (Polynomial with specified roots) :

r = roots(p) which returns a column vector whose elements are the roots
of the polynomial specified by the coefficients row vector p. For vectors,
roots and poly are inverse functions of each other, up to ordering, scaling,
and round off error.

19. tf(Convert unconstrained MPC controller to linear transfer function) :

sys=tf(MPCobj) The tf function computes the transfer function of the


linear controller ss(MPCobj) as an LTI system in tf form corresponding to the
MPC controller when the constraints are not active. The purpose is to use
the linear equivalent control in Control System Toolbox for sensitivity and
other linear analysis.

20. freqz (Frequency response of filter ) :


[h,w] = freqz(ha) returns the frequency response vector h and the
corresponding frequency vector w for the adaptive filter ha. When ha is a
vector of adaptive filters, freqz returns the matrix h. Each column of h
corresponds to one filter in the vector ha.

21. abs (Absolute value and complex magnitude) :

abs(X) returns an array Y such that each element of Y is the absolute


value of the corresponding element of X.

22. fft (Discrete Fourier transform) :


Y = fft(X) Y = fft(X) returns the discrete Fourier transform (DFT) of vector X,
computed with a fast Fourier transform (FFT) algorithm.

23. mod (Modulus after division) :

M = mod(X,Y) returns X - n.*Y where n = floor(X./Y). If Y is not an integer


and the quotient X./Y is within round off error of an integer, then n is that
integer. The inputs X and Y must be real arrays of the same size, or real
scalars.

24. sqrt (Square root) :

B = sqrt(X) returns the square root of each element of the array X. For the
elements of X that are negative or complex, sqrt(X) produces complex
results.

25. ceil (Round toward infinity) :

B = ceil(A) rounds the elements of A to the nearest integers greater than or


equal to A. For complex A, the imaginary and real parts are rounded
independently.
26. fir1(Window-based finite impulse response filter design) :

b = fir1(n,Wn) returns row vector b containing the n+1 coefficients of an


order n lowpass FIR filter. This is a Hamming-window based, linear-phase
filter with normalized cutoff frequency Wn. The output filter coefficients, b,
are ordered in descending powers of z.

27. buttord (Butterworth filter order and cutoff frequency) :

[n,Wn] = buttord(Wp,Ws,Rp,Rs) returns the lowest order, n, of the digital


Butterworth filter that loses no more than Rp dB in the passband and has at
least Rs dB of attenuation in the stopband. The scalar (or vector) of
corresponding cutoff frequencies, Wn, is also returned. Use the output
arguments n and Wn in butter.

28. fliplr (Flip matrix left to right) :

B = fliplr(A) returns A with columns flipped in the left-right direction, that is,
about a vertical axis.If A is a row vector, then fliplr(A) returns a vector of the
same length with the order of its elements reversed. If A is a column vector,
then fliplr(A) simply returns A.

29. min ( Smallest elements in array) :

C = min(A) returns the smallest elements along different dimensions of an


array. If A is a vector, min(A) returns the smallest element in A.If A is a
matrix, min(A) treats the columns of A as vectors, returning a row vector
containing the minimum element from each column. If A is a
multidimensional array, min operates along the first nonsingleton
dimension.

30. max ( Largest elements in array) :

C = max(A) returns the largest elements along different dimensions of an


array.If A is a vector, max(A) returns the largest element in A.If A is a matrix,
max(A) treats the columns of A as vectors, returning a row vector containing
the maximum element from each column. If A is a multidimensional array,
max(A) treats the values along the first non-singleton dimension as vectors,
returning the maximum value of each vector.

31. find (Find indices and values of nonzero elements) :

ind = find(X) locates all nonzero elements of array X, and returns the linear
indices of those elements in vector ind. If X is a row vector, then ind is a row
vector; otherwise, ind is a column vector. If X contains no nonzero elements
or is an empty array, then ind is an empty array.

32. residuez (z-transform partial-fraction expansion ) :

residuez converts a discrete time system, expressed as the ratio of two


polynomials, to partial fraction expansion, or residue, form. It also converts
the partial fraction expansion back to the original polynomial coefficients.

[r,p,k] = residuez(b,a) finds the residues, poles, and direct terms of a partial
fraction expansion of the ratio of two polynomials, b(z) and a(z). Vectors b
and a specify the coefficients of the polynomials of the discrete-time system
b(z)/a(z) in descending powers of z.

33. angle (Phase angle) :

P = angle(Z) returns the phase angles, in radians, for each element of


complex array Z. The angles lie between + π and – π.

34. log (Natural logarithm ) :

Y = log(X) returns the natural logarithm of the elements of X. For complex or


negative z, where z = x +y*i , the complex logarithm is returned.

PART 2
Basic Plotting of Signals
Using MATLAB, make plots of the signals below. Put your code in a Matlab script
file so you can rerun it from the Matlab command after you make revisions to
your life.

Use the subplot command to put several plots on the same page. Print out the plots
and turn them in with your code. Use help subplot to find out how to use the
command.

Use the plot command to plot continuous-time signals. Use the stem command to
plot discrete-time signals. Use help plot and help stem to find out how to
use these commands. Our convention is that f (t) denotes a continuous-time
signal, and that f (n) denotes a discrete-time signal.

Plotting Continuous-Time Signals:


Plotting Discrete-Time Signals:
PROGRAMS:-

Unit Step Sequence :-


% Program for the generation of Unit Step sequence
n = input ('Enter the N value');
t = 0:1:n-1;
y1 = ones(1,n);
subplot(2,2,2);
stem(t,y1);
ylabel('Amplitude---------->');
xlabel('n ---------->');

Output:-

Enter the N value4


(Fig. : Unit Step Sequence)

Unit Impulse :-
% program for the generation of the unit impulse signal
clc;
clear all;
close all;
t=-2:1:2;
y=[zeros(1,2),ones(1,1),zeros(1,2)];
subplot(2,2,1);
stem(t,y);
ylabel('Amplitude.........>');
xlabel('n..........>');

Output:-
(Fig. :- Unit Impulse signal)

Ramp Sequence:-
%Program for the generation of Ramp sequence
clc;
close all;
clear all;
n1 = input('Enter the length of Ramp sequence');
t = 0:n1;
subplot(2,2,3);
stem(t,n1);
ylabel('Amplitude--------->');
xlabel('n------------->');

Output:-
( Fig: Ramp Sequence)

Exponential Sequence:-

%Program for the generation of exponential sequence


clc;
close all;
clear all;
n2 = input('Enter the length of exponential sequence');
t = 0:n2;
a = input('Enter the (a) value');
y2 = exp(a*t);
subplot(2,2,4);
stem(t,y2);
ylabel('Amplitude------------>');
xlabel('n------------>');
Output:-

Enter the length of exponential sequence4

Enter the (a) value2

(Fig: Exponential sequence)

Sine Waveform:-
%Program for the generation of Sine waveform
clc;
close all;
clear all;
t = 0:0.01:pi;
y=sin(2*pi*t);
figure(2);
subplot(2,2,1);
plot(t,y);
ylabel('Amplitude........>');
xlabel('n............>');

OUTPUT:-
(Fig: Sine waveform)

Cosine waveform:-
% Program for the generation of cosine sequence
clc;
close all;
clear all;
t=0:0.01:pi;
y=cos(2*pi*t);
figure(2);
subplot(2,1,1);
plot(t,y);
ylabel('Amplitude.........>');
xlabel('n........>');

OUTPUT:-
(Fig: Cosine waveform)

CONCLUSION:

Hence, from this experiment we concluded that the different types of


basic signals can be represented and synthesized by using MATLAB successfully.
EXPERIMENT NO.-3

AIM:

Write a MATLAB program to perform amplitude –scaling, time-scaling and time


shifting on a given signal by defining functions.

APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PROGRAM:
clear all
close all
%Shifting
t=-2:1:2;
x=[1 2 3 4 5];
subplot(2,2,1);
stem(t,x);
title('input sgnal');
ylabel('ampli--->');
xlabel('n---->');
n=input('enter n value');
t1=t+n;
subplot(2,2,2);
stem(t1,x);
title('shifting');
ylabel('ampli---->');
xlabel('n----->');
%time scaling
t=-2:1:2;
x=[2 3 4 5 6 ];
subplot(2,2,3);
stem(t,x);
title('input signal');
ylabel('ampli---->');
xlabel('n---->');
n=input('enter the value of n');
t1=t.*n;
subplot(2,2,4);
stem(t1,x);
title('time scaling signal');
ylabel('amp---->');
xlabel('n---->');

OUTPUT: [ FOR n=6 and n=4]

input sgnal shifting


6 6

4 4

ampli---->
ampli--->

2 2

0 0
-2 -1 0 1 2 4 5 6 7 8
n----> n----->
input signal time scaling signal
6 6

4 4
ampli---->

amp---->

2 2

0 0
-2 -1 0 1 2 -10 -5 0 5 10
n----> n---->

CONCLUSION:
EXPERIMENT NO.-4

AIM:
1. Write a MATLAB program to obtain linear convolution of the given CT and
DT sequence using the function conv.
2. Compare and verify the result obtained with the expected theoretical results.
APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PROGRAM:

%Program for linear convolution of the sequence


x=[1,2]and h=[1,2,4]

clc;
clear all;
close all;
x=input('enter the 1st sequence');
h=input('enter the 2nd sequence');
y=conv(x,h);
figure;
subplot(3,1,1);
stem(x);
ylabel('Amplitude-->');
xlabel('(a)n-->');
subplot(3,1,2);
stem(h);
ylabel('Amplitude-->');
xlabel('(b)n-->');
subplot(3,1,3);
stem(fliplr(y));
ylabel('Amplitude-->');
xlabel('(c)n-->');
disp('The resultant signal is');
OUTPUT:-

enter the 1st sequence[1 2]

enter the 2nd sequence[1 2 4]

The resultant signal is

CONCLUSION:

From this experiment we have concluded that a program for discrete convolution
can be developed using MATLAB successfully.
EXPERIMENT NO.-5

AIM:
1. Write a MATLAB program to compute autocorrelation of a sequence x(n)
and verify the property.
2. Write a MATLAB program to compute cross-correlation of a sequence x(n)
and y(n) and verify the property.
APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PROGRAM: [CROSS-CORRELATION]
%Program for computing cross correlation of the
%sequences x=[1,2,3,4] and h=[4,3,2,1]
clc;
clear all;
close all;
x=input('enter the 1st sequence');
h=input('enter the 2nd sequence');
y=xcorr(x,h);
figure;
subplot(3,1,1);
stem(x);
ylabel('Amplitude-->');
xlabel('(a)n-->');
subplot(3,1,2);
stem(h);
ylabel('Amplitude-->');
xlabel('(b)n-->');
subplot(3,1,3);
stem(fliplr(y));
ylabel('Amplitude');
xlabel('(c)n-->');
disp('The resultant signal is');
fliplr(y)
OUTPUT:-

CONCLUSION:-

From this experiment we have concluded that a program for the


discrete convolution can be developed using MATLAB successfully.

PROGRAM: [AUTOCORRELATION]
clear all
close all
% Define range of t in the interval [-1;1] with steps of 0.01
t = [-1:.01:1];
% Compute the function with input vector t (with absolute values)
R = 10 * exp(-2 * abs(t));
plot(R);
title('auto-correlation');
xlabel('time index');
ylabel('amplitude');
R
UOTPUT:
auto-correlation
10

7
amplitude

1
0 50 100 150 200 250
time index

SECOND PROGRAM:
clear all;
x=input('enter the sequence x=');
N=length(x);
y=x;
z=x;
for i=1:N-1
for i=N-1:-1:1
x(i+1)=x(i);
end
x(1)=0;
z=[z; x];
end;
m=[z]*[y'];
m=m/N
stem(m);
title('auto-correlation');
xlabel('time index');
ylabel('amplitude');

OUTPUT:
enter the sequence x=[1 3 5]

m=

11.6667
6.0000
1.6667
auto-correlation
12

10

8
amplitude

0
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
time index

EXPERIMENT NO.-6
AIM:
1. To calculate Fourier series coefficients associated with Square Wave and
Triangular wave.
2. To sum the first 10 terms and plot the Fourier series as a function of time.
3. To sum the first 50 terms and plot the Fourier Series as a function of time .
APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PROGRAM: [TRIANGULAR WAVE ]

% FOURIER COEFFICIENTS FOR TRIANGULAR WAVE


clear all;
clc;
close all;
%Triangular wave
t1=0:.001:1;
t2=1.01:.001:2;
x1=2*t1;
x2=-2*t2+4;
x=[x1 x2];
xp=repmat(x,1,4);
t=linspace(-4,4,length(xp));
figure(1)
plot(t,xp,'Linewidth',2,'color','black');
hold on;
plot([0 0],[-4 4],'k',[-4 4],[0,0],'k');
hold off;
axis([-4 4 -4 4]);
ylim([-1 3]);
xlabel('t (seconds)');
ylabel('x(t)');
title('Triangular wave');
%Fourier Series Calculations
syms t k
evalin(symengine,'assume(k,Type::Integer)');
T=2;
w=2*pi/T;
disp('The DC value:');
a0=(1/T)*(int(2*t,0,1)+int(-2*t+4,1,2))
an=(2/T)*(int((2*t)*cos(k*w*t),t,0,1)+int((-2*t+4)*cos(k*w*t),t,1,2));
bn=(2/T)*(int((2*t)*sin(k*w*t),t,0,1)+int((-2*t+4)*sin(k*w*t),t,1,2));
disp('The coefficients are:');
[An]=simple(an)
[Bn]=simple(bn)
x_t=An*(cos(k*w*t))+a0+Bn*sin(k*pi*w*t);
[X_t]=simple(x_t);
disp('x(t)=')
disp(X_t);
disp('The expression of Xn:');
xn=(1/T)*(int((2*t)*exp(-j*k*w*t),t,0,1)+int((-2*t+4)*exp(-j*k*w*t),t,1,2));
[Xn]=simple(xn)
disp('The Power average of x(t)');
Pavg=(1/T)*(int(abs(2*t),0,1)+int(abs((-2*t+4)),1,2))^2

OUTPUT:
Triangular wave
3

2.5

1.5
x(t)

0.5

-0.5

-1
-4 -3 -2 -1 0 1 2 3 4
t (seconds)

The DC value:
a0 =

The coefficients are:

An =

(4*sin(pi*k)^2 - 8*sin((pi*k)/2)^2)/(pi^2*k^2)

Bn =

x(t)=
1 - (cos(pi*k*t)*(2*cos(2*pi*k) - 4*cos(pi*k) + 2))/(pi^2*k^2)

The expression of Xn:

Xn =

(2*(-1)^k - 2)/(pi^2*k^2)

The Power average of x(t)

Pavg =

SQUARE WAVE:

CONCLUSION:

EXPERIMENT NO.-7

AIM:
1. Calculate Fourier Transform of a given signal and plot the magnitude and
the phase spectrum.
2. Calculate the Z-transform of a given signal and plot the poles and zeros of
the Z-transform
APPARATUS REQUIRED:

1. PC installed with MATLAB software (7.12.0(R2011a) version).


2. Printer.

PROGRAM: [FOURIER TRANSFORM]

% FOURIER TRANSFORM OF x(n)=(0.5)^n u(n)


clear all;
close all;
w=[0:1:500]*pi/500; %[0,pi]axis divided into 501 points
X=exp(j*w)./(exp(j*w)-0.5*ones(1,501));
magX=abs(X);
angX=angle(X);
realX=real(X);
imagX=imag(X);
subplot(2,2,1);
plot(w/pi,magX);
grid on
xlabel('frequency in pi units');
ylabel('Magnitude');
title('Magnitude part');
subplot(2,2,3);
plot(w/pi,angX);
xlabel('frequency in pi units');
ylabel('Radians');
title('Angle part')
subplot(2,2,2);
plot(w/pi,realX);
grid on
xlabel('frequency in pi units');
ylabel('real');
title('real part');
subplot(2,2,4);
plot(w/pi,imagX);
grid on
xlabel('frequency in pi units');
ylabel('Imaginary');
title('Imaginary part');

OUTPUT:
Magnitude part real part
2 2
Magnitude

1.5 1.5

real
1 1

0.5 0.5
0 0.5 1 0 0.5 1
frequency in pi units frequency in pi units
Angle part Imaginary part
0 0

-0.2 -0.2
Imaginary
Radians

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8
0 0.5 1 0 0.5 1
frequency in pi units frequency in pi units

Z-TRANSFORM OF x(n)= ¼^n u(n) and pole-zero plot

% Z-TRANSFORM and POLE ZERO PLOT OF x(n)= 1/4^n u(n)


clear all;
close all;
syms z n
ztrans(1/4^n)
b=[0 1 1/2];
a=[1 3/5 2/25];
roots(a)
roots(b)
zplane(b,a)
1

0.8

0.6

0.4
Imaginary Part

0.2

-0.2

-0.4

-0.6

-0.8

-1

-1 -0.5 0 0.5 1
Real Part

CONCLUSION:

EXPERIMENT NO.-8

AIM:
1. Write a MATLAB program to find the impulse response and step response of
a system from its difference equation.[ y(n) = x(n) + x(n-1) – 0.7y(n-1) at
-20 ≤ n ≤ 100.]
2. Compute and plot the sequence of a given system to a given input.
APPARATUS REQUIRED:

3. PC installed with MATLAB software (7.12.0(R2011a) version).


4. Printer.
THEORY:
The impulse response of a given system is its response to impulse function input.
We know that y[n]=impulse response h[n],when input x[n] is unit impulse function
Step response of a system is its output for step function.
ALGORITHM:
1. Start
2. Input the coefficients of x(n).
3. Generate impulse signal.
4. Input the coefficients of y(n).
5. Obtain the impulse response using filter function
6. Plot the impulse response.
7. Generate step signal.
8. Obtain the step response using filter function.
9. Plot the step response.
10. Stop.
MATLAB FUNCTIONS USED:
FILTER: One dimensional digital filter. Y=FILTER (B, A, X) filter the data in
vector X with the filter described by vectors A and B to create the filtered data Y.
The filter is a “Direct Form II Transposed” implementation of the standard
difference equation: a(1) * y(n) = b(1) * x(n) +b(2) * x(n - 1) + .... + b(nb + 1) *
x(n - nb) - a(2) * y(n - 1) - . . . a(na + 1) * y(n - na) If a(1) is not equal to 1, filter
normalizes the filter coefficients by a(1).

PROGRAM:

% IMPULSE AND STEP RESPONSE OF A SYSTEM OF y(n) = x(n) + x(n-1) –


0.7y(n-1)
% at -20 ? n ? 100.
clc
clear all
close all
x = [ 1 1];
y = [1 0.7];
n = -20:1:10;
imp = [zeros(1,20) 1 zeros(1,10)];
h = filter (x, y, imp);
subplot (2, 1, 1);
stem (n,h);
title(' Impulse Response ');
xlabel (' Samples ');
ylabel (' Amplitude ');
stp = [zeros(1,10) 1 ones(1,20)];
h = filter(x,y,stp);
subplot ( 2, 1, 2);
stem(n,h);
title (' Step Response ');
xlabel (' Samples ');
ylabel (' Amplitude ');

OUTPUT:

Impulse Response
1

0.5
Amplitude

-0.5
-20 -15 -10 -5 0 5 10
Samples
Step Response
1.5

1
Amplitude

0.5

0
-20 -15 -10 -5 0 5 10
Samples

CONCLUSION:
EXPERIMENT NO.-9

AIM:
1. For a given system function write a MATLAB program to plot the poles,
zero configuration and Bode plot.
2. Analyze the stability of the given system from the Bode plot
APPARATUS REQUIRED:

5. PC installed with MATLAB software (7.12.0(R2011a) version).


6. Printer.
PROGRAM:[pole-zero plot]

%POLE-ZERO DIAGRAM FOR H(s)=4s2+16s+12/s4+12s3+44s2+48s


clear all;
close all;
num=[0 0 4 16 12];
den=[1 12 44 48 0];
[z,p,k]=tf2zp(num, den)
z
p
zplane(z,p)

OUTPUT:

1
Imaginary Part

-1

-2

-3
-6 -5 -4 -3 -2 -1 0 1
Real Part

BODE DIAGRAM:
FOR
PROGRAM:

%BODE PLOT FOR TF= (20000/(S+20000))


clear all;
close all;
s=tf('s');
H = (20000/(s+20000));
Bode(H)
grid on

OUTPUT:

Bode Diagram
0

-10
Magnitude (dB)

-20

-30

-40
0
Phase (deg)

-45

-90
3 4 5 6
10 10 10 10
Frequency (rad/sec)

STABILITY TEST:
PROGRAM:
%Program for stability test
clc;
clear all;
close all;
b=input('enter the denominator cofficients of the
filter');
k=poly(b);
knew=fliplr(k);
s=all(abs(knew));
if(s==1)
disp('stable system');
else
disp('Non-stable System');
end;

OUTPUT:

enter the denominator coefficients of the filter[1 -1 0.5]

stable system

CONCLUSION:-

From this experiment we have clearly understood the stability test.

BODE PLOT:

PROGRAM:
%MATLAB Code FOR STABILITY FROM BODE PLOT
clear all;
close all;

%BODE_MARGINS_MAT
fig_size = [232 84 774 624];
olz = [-1;-2]; % Transfer function zeros
olp = [0;-.3;-.7+j*2;-.7-j*2;-15]; % Transfer function poles
num = real(poly(olz)); % Numerator polynomial
den = real(poly(olp)); % Denominator polynomial
w = logspace(-3,3,601); % frequency vector
[mag1,ph1] = bode(num,den,w); % open-loop frequency response for K=1
K1 = 2; % 1st Transfer function gain

% Magnitude & Phase plots for K = 2


figure(1),clf,semilogx(w,20*log10(K1*mag1),w,ph1),grid,xlabel('Frequency
(r/s)'),...
ylabel('Magnitude (db) & Phase (deg)'),...
title('Bode Magnitude and Phase Plots, K = 2'),set(gcf,'Position',fig_size)

% Magnitude & Phase plots for K = 2


% with gain and phase margins and crossover frequencies shown
figure(2),clf,semilogx(w,20*log10(K1*mag1),w,ph1),grid,xlabel('Frequency
(r/s)'),...
ylabel('Magnitude (db) & Phase (deg)'),...
hold on,semilogx([min(w) max(w)],[-180 -180],'r--',[min(w) max(w)],[0
0],'r--'),hold off,...
title('Gain and Phase Margins, K = 2'),set(gcf,'Position',fig_size)
[gm1,pm1,wphi1,wx1] = margin(K1*num,den); % gain and phase margins
dcl1 = den + K1 * [0 0 0 num];
clp1 = roots(dcl1); % closed-loop poles
hold on,semilogx([wphi1 wphi1],[-20*log10(gm1) 0],'m--'),hold off
hold on,semilogx([wx1 wx1],[-180 -180+pm1],'m--'),hold off

K2 = 25; % 2nd Transfer function gain


% Magnitude & Phase plots for K = 25
% with gain and phase margins and crossover frequencies shown
figure(3),clf,semilogx(w,20*log10(K2*mag1),w,ph1),grid,xlabel('Frequency
(r/s)'),...
ylabel('Magnitude (db) & Phase (deg)'),...
hold on,semilogx([min(w) max(w)],[-180 -180],'r--',[min(w) max(w)],[0
0],'r--'),hold off,...
title('Gain and Phase Margins, K = 25'),set(gcf,'Position',fig_size)
[gm2,pm2,wphi2,wx2] = margin(K2*num,den); % gain and phase margins
dcl2 = den + K2 * [0 0 0 num];
clp2 = roots(dcl2); % closed-loop poles
hold on,semilogx([wphi2 wphi2],[-20*log10(gm2) 0],'m--'),hold off
hold on,semilogx([wx2 wx2],[-180 -180+pm2],'m--'),hold off

K3 = 400; % 3rd Transfer function gain


% Magnitude & Phase plots for K = 400
% with gain and phase margins and crossover frequencies shown
figure(4),clf,semilogx(w,20*log10(K3*mag1),w,ph1),grid,xlabel('Frequency
(r/s)'),...
ylabel('Magnitude (db) & Phase (deg)'),...
hold on,semilogx([min(w) max(w)],[-180 -180],'r--',[min(w) max(w)],[0
0],'r--'),hold off,...
title('Gain and Phase Margins, K = 400'),set(gcf,'Position',fig_size)
wphi3 = wphi1;
gm3 = gm1/200;
wx3 = 5.5123;
pm3 = -30.6922;
dcl3 = den + K3 * [0 0 0 num];
clp3 = roots(dcl3); % closed-loop poles
hold on,semilogx([wphi3 wphi3],[-20*log10(gm3) 0],'m--'),hold off
hold on,semilogx([wx3 wx3],[-180 -180+pm3],'m--'),hold off

OUTPUT:
Bode Magnitude and Phase Plots, K = 2
50

0
M agnitude (db) & P hase (deg)

-50

-100

-150

-200

-250

-300
-3 -2 -1 0 1 2 3
10 10 10 10 10 10 10
Frequency (r/s)

Gain and Phase Margins, K = 2


50

0
M agnitude (db) & P hase (deg)

-50

-100

-150

-200

-250

-300
-3 -2 -1 0 1 2 3
10 10 10 10 10 10 10
Frequency (r/s)
Gain and Phase Margins, K = 25
100

50
M agnitude (db) & P has e (deg)

-50

-100

-150

-200

-250

-300
-3 -2 -1 0 1 2 3
10 10 10 10 10 10 10
Frequency (r/s)

Gain and Phase Margins, K = 400


100

50

0
M agnitude (db) & P hase (deg)

-50

-100

-150

-200

-250

-300
-3 -2 -1 0 1 2 3
10 10 10 10 10 10 10
Frequency (r/s)
EXPERIMENT NO.-10

AIM:
1. Write a MATLAB program to plot the frequency response of the first order
system.
2. Also write MATLAB program to calculate the rise time and bandwidth of
same system.
APPARATUS REQUIRED:

7. PC installed with MATLAB software (7.12.0(R2011a) version).


8. Printer.
THEORY:

The frequency response of a system is the major way of characterizing how a


system behaves in the frequency domain. It is important to understand the
frequency characteristics of a given system rather than time domain characteristics
alone for many practical applications like filter design.

The frequency response of a system, H ( ) is just the transfer function,


H (s ) evaluated at s  j . Frequency response is usually a complex valued
function, so it can be written as H ( )  H ( ) H ( ) , where H ( ) is the
magnitude response and H ( ) is the phase response. You can use MATLAB to
plot the magnitude and phase responses as follows:
( s  1) s 1
Example: H ( s)  ( s  4) 2  s 2  8s  8 , to plot magnitude and phase responses use the
following command lines. Define two vectors b and a where b is the coefficients of
the polynomial in the numerator, and a is the coefficients of the polynomial in the
numerator.

Note that they have to be the same length and start with the coefficient of the
highest order term. Then define w as the vector of frequencies over which you
want to plot the magnitude and phase responses.

PROGRAM:

% FREQUENCY RESPONSE OF A SYSTEM


clear all;
close all;
b=[0 1 -1];
a=[1 8 8];
w=[0:.1:2*pi];
freqs(b,a,w)

OUTPUT:
-0.87
10
Magnitude

-0.96
10
-1 0
10 10
Frequency (rad/s)

200
Phase (degrees)

100

-100
-1 0
10 10
Frequency (rad/s)

RISE TIME CALCULATION:


PROGRAM:

clear all;
close all;
sys = tf([1 5],[1 2 5 7 2]);
S = stepinfo(sys,'RiseTimeLimits',[0.05,0.95]);
S
fb = bandwidth(sys);% bandwidth in radians
fb

OUTPUT:
S=
RiseTime: 7.4454
SettlingTime: 13.9378
SettlingMin: 2.3737
SettlingMax: 2.5201
Overshoot: 0.8032
Undershoot: 0
Peak: 2.5201
PeakTime: 15.1869

fb =

0.3724

CONCLUSION:

You might also like