You are on page 1of 90

# EC 45

IV Semester

Rajesh N

## Dept of Electronics and Communication Engg

Nitte Meenakshi Institute of Technology
Yelahanka, Bangalore – 560 064
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Syllabus
Part - A ( 8 Lab Sessions of 3Hrs Each)
(Perform the experiments using MatLab)

## 1. Vector and matrix operations, solving non linear equations.

2. a) Representation of basic signals, Basic operations on continuous/discrete time
signals: Add/sub of two signals, scaling, shifting, time reversal , signal energy /
power calculation
b) Verification of Shannon sampling theorem.
3. Convolution and Correlation of continuous/ discrete time signals.
4. Fourier analysis of signals: Computing CTFS/CTFT and DTFS/DTFT, properties of
DTFT
5. The z and Inverse z-Transform: Properties of z-Ttransform. Determination of
system function and the unit sample response of a linear time invariant systems
described by difference equation.
6. Laplace Transform analysis of linear systems.
7. PID design.
8. Frequency response analysis: Bode Plots , Nyquist Plot. Root Locus
9. Simulink model of first /second order systems.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

2
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

EXPERIMENT No.1

## Vector and matrix operations, solving non linear equations.

Aim: Study Vector and matrix operations and solving non linear equations.

## Refer Appendix for vector and matrix operations.

Example:1. Solve the given quadratic equation
x2 + 5x +6 = 0
roots = -3 and -2
program: b=[1 5 6];
roots(b)
Result:
ans =
-3.0000
-2.0000
Example:2. Solving given difference equation

Theory:
• A difference equation with constant coefficients describes a LTI system. For example
the difference equation y[n] + 0.8y[n-2] + 0.6y[n-3] = x[n] + 0.7x[n-1] + 0.5x[n-2]
describes a LTI system of order 3. The coefficients 0.8, 0.7, etc are all constant i.e.,
they are not functions of time (n). The difference equation y[n]+0.3ny[n-1]=x[n]
describes a time varying system as the coefficient 0.3n is not constant.
• The difference equation can be solved to obtain y[n], the output for a given input x[n]
by rearranging as y[n] = x[n] + 0.7x[n-1]+0.5x[n-2]- 0.8y[n-2]- 0.6y[n-3] and solving.
• The output depends on the input x[n]
o With x[n]= δ[n], an impulse, the computed output y[n] is the impulse
response.
o If x[n]=u[n], a step response is obtained.
o If x[n] = cos(wn) is a sinusoidal sequence, a steady state response is obtained
(wherein y[n] is of the same frequency as x[n], with only an amplitude gain
and phase shift-refer Fig.7.3).
o Similarly for any arbitrary sequence of x[n], the corresponding output
response y[n] is computed.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

3
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

• The difference equation containing past samples of output, i.e., y[n-1], y[n-2], etc
leads to a recursive system, whose impulse response is of infinite duration (IIR). For
such systems the impulse response is computed for a large value of n, say n=100 (to
approximate n=∞). The MATLAB function filter is used to compute the impulse
response/ step response/ response to any given x[n]. Note: The filter function
evaluates the convolution of an infinite sequence (IIR) and x[n], which is not possible
with conv function (remember conv requires both the sequences to be finite).
• The difference equation having only y[n] and present and past samples of input (x[n],
x[n-k]), represents a system whose impulse response is of finite duration (FIR). The
response of FIR systems can be obtained by both the ‘conv’ and ‘filter’ functions. The
filter function results in a response whose length is equal to that of the input x[n],
whereas the output sequence from conv function is of a longer length (xlength +
hlength-1).
Algorithm:
1. Input the two sequences as a and b representing the coefficients of y and x.
2. If IIR response, then input the length of the response required (say 100, which can be
3. Compute the output response using the ‘filter’ command.
4. Plot the input sequence & impulse response (and also step response, etc if required).

MATLAB Implementation:
MATLAB has an inbuilt function ‘filter’ to solve difference equations numerically, given
the input and difference equation coefficients (b,a).
y=filter(b,a,x)
where x is the input sequence, y is the output sequence which is of same length as x.
Given a difference equation a0y[n]+a1y[n-1]+a2y[n-2]=b0x[n]+b2x[n-2], the coefficients are
written in a vector as b=[b0 0 b2] and a=[a0 a1 a2]. Note the zero in b (x[n-1] term is missing).
Also remember a0, the coefficient of y[n] should always be 1.
For impulse response x[n] = {1,0,0,0,....} the number of zeros = the length of the IIR response

## required (say 100 implemented by function zeros(1,99)).

For step response x[ n] = {1,1,1,1,1,....} the number of ones = the length of the IIR response

## required-1 (say 100 implemented by function ones(1,100).

Similarly for any given x[n] sequence, the response y[n] can be calculated.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

4
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

MATLAB Program:
clear all, close all ;
%y(n)-0.1y(n-1)=x(n)
%x(n)=u(n)
%initial condition y(-1)=2
b=input('Enter the numerator co-effiecients')
a=input('Enter the denominator co-effiecients')
N=input('Enter the length of the input sequence')
n=0:1:N-1;
inp=1.^n;
X=2;
XIC=filtic(b,a,X);
RES1=filter(b,a,inp,XIC);
figure(1);
stem(n,RES1); grid on;
xlabel('n');
ylabel('amplitude');
title('step response output of difference equation');

## %x(n) is an impulse function

IMP=[1,zeros(1,50)];
RES2=filter(b,a,IMP,XIC);
n=0:1:length(RES2)-1;
figure(2);
stem(n,RES2); grid on;
xlabel('n');
ylabel('amplitude');
title('impulse response output of difference equation');

RESULTS:

## Enter the numerator co-effiecients[1]

b= 1
Enter the denominator co-effiecients[1 -0.1]
a= 1.0000 -0.1000
Enter the length of the input sequence50
N = 50

RES1=
1.2000, 1.1200, 1.1120, 1.1112, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111,
1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111,
1.1111, 1.1111 , 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111,
1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111,
1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111, 1.1111,
1.1111, 1.1111, 1.1111, 1.1111, 1.1111

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

5
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

RES2=
1.2000, 0.1200, 0.0120, 0.0012, 0.0001, 0.0000, 0.0000, 0.0000, 0.0000
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000

Questions:
1)Difference equation y(n) - y(n-1) + 0.9y(n-2) = x(n);
Calculate impulse response h(n) and also step response at n=0,…..,100
2)Plot the steady state response y[n] to x[n]=cos(0.05πn)u(n), given y[n]-0.8y[n-1]=x[n]

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

6
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

*note- Use [h,t]=impz(b,a,N) to find the impulse response and find the difference
between y~=h’ (=0).
Using impz, we need not specify the impulse input x[n], just the coefficients and
length N that we desire (refer experiment 2).

Example: Find the first 8 samples of the complete response y[n] for the difference equation
1
y[n] = [x[n] + x[n − 1] + x[n − 2]] + 0.95 y[n − 1] − 0.9025 y[n − 2]; n≥0; where
3
⎛ πn ⎞
x[n] = cos⎜ ⎟u[ n] and the initial conditions are y[-1]=-2; y[-2]=-3; x[-1]=1; x[-2]=1.
⎝ 3 ⎠

Solution: Use MATLAB function filter(b,a,x,xic), where xic are the initial conditions
computed as xic=filtic(b,a,Y,X), where Y=[y(-1) y(-2)…y(N-1)] & X=[x(-1) x(-2)…x(-M)]
are the initial condition arrays. If x[n]=0 for n<0, then X need not be specified.

## The sample program for the above problem is:

b=[1/3 1/3 1/3]; a=[1 -0.95 0.9025]; %difference equation coefficient arrays
Y=[-2 -3]; X=[1 1]; %initial condition arrays
xic=filtic(b,a,Y,X);
n=0:7; %For 8 output samples using filter function, the input should also be of size 8
x=cos(pi*n/3); %input sequence
y=filter(b,a,x,xic); %output response
Answer: y = 1.8075 4.3555 2.8398 -1.5664 -4.7176 -3.4014 1.3596 5.0281

Exercises:
1. Implement all the exercises given in chapter-2: “S&S”, M.J.Roberts.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

7
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

EXPERIMENT No.2

## %Unit step function defined as 0 for input argument values

%Less than zero, ½ for input argument values equal to zero,
%And one for input argument values greater than zero.

function y=u(t)
zero=(t==0) ;pos =(t>0) ;y=zero/2 + pos ;

## % function to compute the triangle function.uses the definition

% of the triangle functionin terms of the ramp function.works
% for vectors and scalars equally well.
function y=tri(t)
y=ramp(t+1) -2*ramp(t) + ramp(t-1) ;

## % function to compute sinc(t) defined as sin(pi*t)/(pi*t) .

% works for vectors or scalars equally well.this function
% may be intrinsic in some versions of MATLAB.
function y=sinc(t)
zero=(t==0) ; % indicate the locations of zeros in t.
num=(~zero).*sin(pi*t) + zero ; den = (~zero).*(pi*t) +zero ;
y=num./den ;

## % rectangle function . uses the definition of the rectangle

% function in terms of the unit step function.works on
% vectors or scalars equally well.
function y=rect(t)
y=u(t+0.5) - u(t-0.5) ;

## % Function to compute the ramp function defined as zero for

% Values of the argument less than zero and the value of
% The argument for arguments greater than or equal to zero.
% Works for vectors and scalars equally well.
function y=ramp(t)
y=t.*(t >=0) ;

## % Function to generate the discrete-time impulse function defined as one

% for input integer arguments equal to zero and zero otherwise .
% Returns- NaN for noninteger arguments .Works for vectors and
% Scalars equally well .

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

8
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

function y=impDT(n)

## y=(n==0) ; % impulse is one where argument

% is zero and zero otherwise.
ss=find(round(n)~=n) % Find noninteger values of n..
y(ss)==NaN ; % Set corresponding outputs to NaN.

## % function to compute values of the dirichlet function.

% Works for vectors or scalars equally well.
% x= sin(N*pi*t)/(N*sin(pi*t))
function x =drcl(t,N)
x=diric(2*pi*t,N) ;

## % program to demonstrate some basic CT signals

%--------------------------------------------------------------------------------
clc;
disp('Select the finction')
%----Next part of the program accepts choice of function --------------------

## Choice = input('Enter choice of function = ');

t=-10:0.1:10;

switch(Choice)
case{1} % Sine
plot(t,sin(t)); grid on

case{2} % Exponential
plot(t,exp(t)); grid on

case{3} % Ramp
plot(t,(t.*(t >=0))); grid on

case{4} % Step
plot(t,(t>=0)); grid on

case{5} % Rectangle
plot(t,(t>=-1&t<=1)); grid on

case{6} % Sinc
plot(t,((~(t==0)).*sin(pi*t) + (t==0))./ ((~(t==0)).*(pi*t) +(t==0))); grid on

otherwise
subplot(321); plot(t,sin(t)); grid on; title('Sine Wave')
subplot(322); plot(t,exp(t)); grid on ; title('Exponential')
subplot(323); plot(t,(t.*(t >=0))); grid on ; title('Ramp')
subplot(324); plot(t,(t>=0)); grid on ; title('Step')
subplot(325); plot(t,(t>=-1&t<=1)); grid on; title('Rectangle')
subplot(326); plot(t,((~(t==0)).*sin(pi*t) + (t==0))./ ((~(t==0)).*(pi*t) +(t==0))); grid on;title('Sinc')
end

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

9
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## Discrete time Signals

---------------------------------------------------------------------------------------------------------------

## % program to plot some demonstrations of CT function combination.

% x1(t) = exp(-t).sin(20.pi.t)+exp(-t/2)sin(19.pi.t)
% x2(t) = sinc(t)cos(20.pi.t).

## t=0:1/120:6; x1 =exp(-t).*sin(20*pi*t) + exp(-t/2).*sin(19*pi*t) ;

subplot(2,1,1); p=plot(t,x1,'k'); set(p,'LineWidth',2) ;
xlabel('\itt'); ylabel('x_1({\itt})') ;
t=-4:1/60:4; x2 =sinc(t).*cos(20*pi*t);
subplot(2,1,2); p=plot(t,x2,'k'); set(p,'LineWidth',2) ;
xlabel('\itt'); ylabel('x_2({\itt})') ;

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

10
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

g.m
function y=g(t)
%calculate the functional variation for each range of t.
y1=-4 -2*t ;y2= -4 +3*t ;y3=16 -2*t ;
%splice together the different functional variations in their respective ranges of validity.
y=y1.*(-2<t & t<=0) +y2.*(0<t & t<=4) +y3 .*(4<t & t<=8) ;

Script file:
% program to plot the function ,g(t) and then to
% plot 3*g(t+1) ,g(3*t)/2 ,and -2*g(t-1)/2 .
% Write a function for g(t) and store.

tmin =-4 ; tmax =20; % set the time range for the plot .
dt=0.1 ; % set the time between points
t=tmin:dt:tmax; % set the vector of times for the plot.
g0=g(t) ; % compute the original g(t).
g1=3*g(t+1) ; % compute the first transformation .
g2=g(3*t) /2 ; % compute the second transformation .
g3=-2*g((t-1)/2) ; % compute the third transformation .

## % Find the maximum and minimum g values in all the transformed

% Functions and use them to scale all plots the same .
gmax=max([max(g0) ,max(g1) ,max(g2) ,max(g3)]) ;
gmin=min([min(g0) ,min(g1) ,min(g2) ,min(g3)]) ;
% plot all four functions in a 2 by 2 arrangement .
% plot them all on the same scale using the axis command .
% plot grid lines, using the grid command ,to aid in reading values.
Subplot (2,2,1); p=plot(t,g0,'k'); set(p,'linewidth',2) ;
xlabel('t');ylabel('g(t)'); title('Original Function, g(t)');
axis([tmin,tmax,gmin,gmax]);grid;
subplot(2,2,2); p=plot(t,g1,'k') ; set (p,'LineWidth',2);
xlabel('t'); ylabel('3g(t+1)'); title ('First Transformation');
axis([tmin,tmax,gmin,gmax] ) ;grid;
subplot(2,2,3);p=plot(t,g2,'k'); set(p,'LineWidth',2);
xlabel('t');ylabel('g(3t)/2');title('Second Transformation');
axis([tmin,tmax,gmin,gmax] );grid;
subplot(2,2,4); p=plot(t,g3,'k'); set(p,'LineWidth',2);
xlabel('t'); ylabel('-2g((t-1)/2)');title('Third Transformation');
axis([tmin,tmax,gmin,gmax] );grid ;

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

11
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

---------------------------------------------------------------------------------------------------------------------------
% program to illustrate some of MATLAB s built-in functions
% close all ;
t= -20:1/20:20 ;
x1=chirp(t,1/20,20,1/3) ; subplot(4,2,1) ; p=plot(t,x1, 'k' ) ;
axis([-20,20,-1.5,1.5] ) ; title( 'chirp - A "chirped" cosine') ;
xlabel ( '\itt') ; ylabel( 'x_1({\itt })') ;
x2=diric(t,5) ; subplot (4,2,2) ; p=plot(t,x2, 'k') ;
axis([-20,20, -1.5, 1.5] ) ;
title ( 'diric -The MATLAB "Dirichlet" function') ;
xlabel( ' \ itt') ; ylabel( 'x_2({\itt})') ;
x3=sawtooth(t) ; subplot(4,2,3) ;p=plot(t,x3, 'k') ;
axis([-20,20 -1.5 ,1.5] ) ; title( 'sawtooth -A Periodic Sawtooth') ;
xlabel( '\ itt') ; ylabel( 'x_3({\itt})') ;

## x4=square(t) ;subplot(4,2,4) ; p=plot(t,x4, 'k') ;

axis([-20,20, -1.5, 1.5] ) ;title( 'square - A Square Wave') ;
xlabel( '\itt') ; ylabel( 'x_4({\itt })') ;

## x5=rectpuls(t/10) ; subplot(4,2,5) ; p =plot(t,x5, 'k') ;

axis([ -20 ,20 ,-1.5 ,1.5] ) ; title( 'rectpuls - A Rectangular Pulse Wave') ;
xlabel( '\itt') ; ylabel ( 'x_5 ({\itt})' );

## x6=tripuls(t/10) ; subplot (4,2,6) ; p=plot(t,x6, 'k') ;

axis([ -20 ,20 , -1.5 ,1.5] ) ; title( 'tripuls -A Triangular Pulse Wave') ;
xlabel ( '\itt') ;ylabel( 'x_6({\itt})') ;

## x7=sinc(t/2) ; subplot(4,2,7) ; p=plot(t,x7, 'k') ;

axis([ -20 ,20 ,-1.5 ,1.5]) ; title( 'sinc(t)') ;
xlabel ( '\itt') ;ylabel( 'x_7({\itt})' );

## x8=sign(t/2) ; subplot(4,2,8) ; p=plot(t,x8, 'k') ;

axis([ -20 ,20 -1.5 ,1.5] ) ; title( 'sign - The Signum Function') ;
xlabel( '\itt') ; ylabel( 'x_8({\itt })') ;

figure;
x24=x2.*x4 ;
subplot(2,2,1) ; plot(t,x24, 'k') ;
axis([ -20 ,20 ,-1.5 ,1.5] ) ; title( 'x_2*x_4 - Even*odd') ;
xlabel( '\itt') ; ylabel( 'x_2_4({ \itt})') ;

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

12
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

x34=x3 .*x4 ;
subplot(2,2,2) ; plot(t,x34 , 'k') ;
axis([ -20 ,20 ,-1.5 ,1.5] ) ; title( 'x_3*x_4 -odd*odd') ;
xlabel( '\itt') ; ylabel( 'x_3_4({\itt})') ;

x26=x2 .*x6 ;
subplot(2,2,3) ; plot(t,x26 , 'k') ;
axis([ -20 ,20 ,-1.5 ,1.5]) ; title( 'x_2*x_6 - Even*Even') ;
xlabel( '\itt') ;ylabel( 'x_2_6({\itt})') ;

x37=x3 .*x7 ;
subplot(2,2,4) ; plot(t, x37 , 'k') ;
axis([ -20 ,20 , -1.5 ,1.5] ) ; title( 'x_3*x_7 - odd*Even') ;
xlabel( '\itt') ; ylabel( 'x3_7({\itt})') ;

## xle= (x1 + x1(end: -1 :1)) /2 ; xlo= (x1 - x1(end : -1 :1))/2 ;

subplot(2,1,1) ; plot(t,xle, 'k') ;
axis([ -20 ,20 , -1.5 ,1.5] ) ; title( 'Even Part of x_1') ;
xlabel( '\itt') ; ylabel( 'x_1_e({\itt})') ;
subplot(2,1,2) ; plot(t ,xlo , 'k') ;
axis( [ -20 ,20 ,-1.5 ,1.5] ) ; title( 'odd Part of x_1') ;
xlabel( '\itt') ; ylabel ( 'x_1_o({\itt})') ;

## % pole zero plot from coefficients of a difference equation.

% This Matlab program accepts the coefficients of the difference equation
% and generates pole zero plot against the unit circle.
%
% The format of the difference equation is as follows..

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

13
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## % y(n) = -[a1*y(n-1) + a2*y(n-2) + a3*y(n-3) + ....]

% +b0*x(n) + b1*x(n-1) + b2*x(n-2) + ....

## % a0*y(n) + [a1*y(n-1) + a2*y(n-2) + a3*y(n-3) + ....

% = b0*x(n) + b1*x(n-1) + b2*x(n-2) + ....

## % here a0 = 1 and the coefficients are to be entered as,

% b = [b0 b1 b2 b3 . . .]
% a = [a0 a1 a2 a3 . . .]

## %----- Next part accepts coefficients of the difference equation ----------------

clc;
disp(' Pole zero plot'); disp(' ');
b = input('enter [b0 b1 b2...] = '); % enter the coefficients of x(n)
a = input('enter [a0 a1 a2...] = '); % enter the coefficients of y(n)

## zplane(b,a); % plot the pole zero plot

title('Pole zero plot');

## Aim: To verify Sampling theorem for a signal of given frequency.

Theory:
• Sampling is a process of converting a continuous time signal (analog signal) x(t) into
a discrete time signal x[n], which is represented as a sequence of numbers. (A/D
converter)
)
• Converting back x[n] into analog (resulting in x (t ) ) is the process of reconstruction.
(D/A converter)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

14
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## • Techniques for reconstruction-(i) ZOH (zero order hold) interpolation results in a

staircase waveform, is implemented by MATLAB plotting function stairs(n,x), (ii)
FOH (first order hold) where the adjacent samples are joined by straight lines is
implemented by MATLAB plotting function plot(n,x),(iii) spline interpolation, etc.
)
• For x (t ) to be exactly the same as x(t), sampling theorem in the generation of x(n)
from x(t) is used. The sampling frequency fs determines the spacing between samples.
• Aliasing-A high frequency signal is converted to a lower frequency, results due to
under sampling. Though it is undesirable in ADCs, it finds practical applications in
stroboscope and sampling oscilloscopes.

## The Sampling Theorem:

If a signal xa(t) has a bandlimited Fourier transform Xa(jΩ) such that Xa(jΩ)=0 for Ω≥2πfN,
then xa(t) can be uniquely reconstructed from equally spaced samples xa(nT), -∞<n<∞, if
1/T≥2 fN (fS≥2fN).

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

15
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## To avoid aliasing need :

2π / T − Ω N > Ω N or 2π / T > 2 Ω N or
1 / T > 2 FN

## case where 1 / T < 2 FN ,

aliasing occurs

x
fs >= 2 * highest freq in x

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

16
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## Plots of a sampled cosine wave of 200Hz

Algorithm:
1. Input the desired frequency fd (for which sampling theorem is to be verified).
2. Generate an analog signal xt of frequency fd for comparison.
3. Generate oversampled, Nyquist & under sampled discrete time signals.
4. Plot the waveforms and hence prove sampling theorem.

MATLAB Program:
close all, clear all;;
f=5;
fs=2*f;
n4=-50:1:50;

% for fs >> fm
n=0.01:0.01:1;
%a=1+sin(2*pi*f*n)+(1+sin(2*pi*2*f*n))/2+(1+sin(2*pi*3*f*n))/3;
a=(1+cos(2*pi*f*n));
figure(1);
subplot(4,1,1);plot(a);grid on;
subplot(4,1,2);stem(a);grid on;
b=fft(a,101);
b=fftshift(b);
subplot(4,1,3); stem(n4,abs(b));grid on;
s=abs(ifft(b)); s=s(1:100);
subplot(4,1,4); plot(s); grid on;

% for fs = fm
n2=0:1/(fs/2):1;
%a1=1+sin(2*pi*f*n2)+(1+sin(2*pi*2*f*n2))/2+(1+sin(2*pi*3*f*n2))/3;
a1=(1+cos(2*pi*f*n2));
figure(2);
subplot(4,1,1);plot(a);grid on;
subplot(4,1,2);stem(a1);grid on;
b=fft(a1,101);

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

17
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

b=fftshift(b);
subplot(4,1,3); stem(n4,abs(b));grid on;
g1=abs(ifft(b,101));
subplot(4,1,4); plot(g1(1:length(n2)),'r'); grid on;

% for fs =2* fm
n1=0:1/(fs):1;
%a2=1+sin(2*pi*f*n1)+(1+sin(2*pi*2*f*n1))/2+(1+sin(2*pi*3*f*n1))/3;
a2=(1+cos(2*pi*f*n1));
figure(3);
subplot(4,1,1);plot(n*100,a);grid on;
subplot(4,1,2);stem([a2]);grid on;
b=fft(a2,101);
b=fftshift(b);
subplot(4,1,3); stem(n4,abs(b));grid on;
g=abs(ifft(b,101));
subplot(4,1,4); plot(g(1:length(n1)),'r'); grid on;

## % for fs =2*(2* fm)

n3=0:1/(2*fs):1;
%a2=1+sin(2*pi*f*n3)+(1+sin(2*pi*2*f*n3))/2+(1+sin(2*pi*3*f*n3))/3;
a2=(1+cos(2*pi*f*n3));
figure(4);
subplot(4,1,1);plot(n*100,a);grid on;
subplot(4,1,2);stem(n3*100,a2);grid on;
b=fft(a2,101);
b=fftshift(b);
subplot(4,1,3); stem(n4,abs(b));grid on;
g=abs(ifft(b,101));
subplot(4,1,4); plot(n3*100, g(1:length(n3)),'r'); grid on;

Result:

fs>>fm

Fig: a) 5Hz sinusoidal time domain signal b) Sampled sequence at high sampling rate. c) Spectrum. d)
Reconstructed signal.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

18
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

fs=fm

Fig: a) 5Hz sinusoidal time domain signal b) Sampled sequence at half the Nyquist rate. c) Spectrum. d)
Reconstructed signal.

fs=2*fm

Fig: a) 5Hz sinusoidal time domain signal b) Sampled sequence at Nyquist rate. c) Spectrum. d) Reconstructed
signal.

fs=2*(2*fm)

Fig: a) 5Hz sinusoidal time domain signal b) Sampled sequence at double the Nyquist rate. c) Spectrum. d)
Reconstructed signal.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

19
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## Note: Mark the labeling for above graphs.

Inference:From the under sampling plot observe the aliasing effect. The analog signal is of
5Hz. The reconstructed (from under sampled plot) signal is of a lower frequency.
At Nyquist rate plot shows a reconstructed signal almost similar to that of the analog signal.
Using low pass filtering the wave form can be further smoothened.
The over sampled plot shows a reconstructed signal similar to that of the analog signal.

Questions:
1. Generate sine/cosine waveforms of multiple frequencies, say x1=sin(2*pi*fd1*n1)+
sin(2*pi*fd2*n2); where fd1, fd2 are 2 different frequencies.
2. Sample a band limited continuous time signal band limited to fm = 3400 Hz under the
following conditions
a. Nyquist Rate b. Twice the Nyquist Rate c. Half the Nyquist rate.

## Impulse response of a given system

Aim: To find the impulse response h(n) of the given LTI system whose response y(n) to an
input x(n) is given.

Theory:

## Fig.2.1: A LTI system

• A discrete time LTI system (also called digital filters) as shown in Fig.2.1 is
represented by
o A linear constant coefficient difference equation, for example,
y[n] + a1 y[n − 1] − a 2 y[n − 2] = b0 x[n] + b1 x[n − 1] + b2 x[n − 2];
o A system function H(z) (obtained by applying Z transform to the difference
Y ( z ) b0 + b1 z −1 + b2 z −2
equation). H ( z ) = =
X ( z ) 1 + a1 z −1 + a 2 z − 2
o A frequency response function obtained by applying DTFT on the impulse
response h[n] (or by replacing z with ejΩ in H(z)) to get
jΩ Y (e jΩ ) b0 + b1e − jΩ + b2 e −2 jΩ
H (e ) = =
X (e jΩ ) 1 + a1e − jΩ + a 2 e − 2 jΩ
• Given the difference equation or H(z), the impulse response of the LTI system is
computed using filter or impz MATLAB functions. This is elaborated in experiment
no.7 - Solving a given difference equation. If the difference equation contains past
samples of output, i.e., y[n-1], y[n-2], etc , then its impulse response is of infinite

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

20
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

duration (IIR). For such systems the impulse response is computed for a large value of
n, say n=100 (to approximate n=∞).
• Given only the input sequence x[n] and the output sequence y[n], we can find the
impulse function h[n] by using the inverse operation deconv. (The conv operation
convolves 2 sequences x[n] and h[n] to obtain the output y[n]. for convolution
operation refer experiment no 3: Linear convolution of two given sequences). If both
y[n] and x[n] are finite then the impulse response is finite (FIR).
• The deconvolution operation is valid only if the LTI system is ‘invertible’.

Given Problem
1) Find the impulse response h(n) of the given LTI system whose response y(n)=[1 2 3 2 1 2 ]
to an input x(n)=[1 2 3] is given. Also verify the result using conv operation. (FIR)
2) A LTI system is described by the difference equation y(n) - y(n-1) + 0.9y(n-2) = x(n);
Find its impulse response h(n) at n=0,…..,50. (IIR)

## Algorithm for Problem1:

1. Input the two sequences as x and y.
2. Use deconv to get impulse response h.
3. Plot the sequences.
4. Verify using conv(x,h) to get y back.

## Algorithm for Problem2:

1. Input the two coefficient arrays as b and a.
2. Input the length of the impulse response required as N.
3. Use impz unction to get impulse response h.
4. Plot the impulse response.

MATLAB Implementation:
h=deconv(y,x): ‘y’ the output sequence should be of longer length than x. DECONV -
Deconvolution and polynomial division. [Q,R] = DECONV(B,A) deconvolves vector A out
of vector B. The result is returned in vector Q and the remainder in vector R such that B =
conv(A,Q) + R. If A and B are vectors of polynomial coefficients, deconvolution is
equivalent to polynomial division. The result of dividing B by A is quotient Q and remainder
R. (Remember conv is polynomial multiplication).

Note: Valid y and x should be given, else the conv verification will result in a slightly
different y (because of the remainder generated by deconv).

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

21
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

h=impz(b,a,N), returns the impulse response h[n], where b and a are coefficient arrays
obtained from difference equation, N = length of the response required. (refer expt.7). For the
given difference equation b=[1]; a=[1 -1 0.9].
IMPZ Impulse response of digital filter. [H,T] = IMPZ(B,A) computes the impulse response
of the filter B/A choosing the number of samples for you, and returns the response in column
vector H and a vector of times (or sample intervals) in T (T = [0 1 2 ...]').
[H,T] = IMPZ(B,A,N) computes N samples of the impulse response.

MATLAB Programs:
Program 1:
y= input('The output sequence y(n) of the system=');
x=input('the input sequence of the system=');
h=deconv(y,x);
disp('the impulse response of the system is=');
disp(h);

## %graphical display part

N=length(h);
n=0:1:N-1;
stem(n,h);
xlabel('Time index n');
ylabel('Amplitude');
title('impulse response of a system')

%Verification
yv=conv(x,h);
disp('the verified output sequence is');
disp(yv)

Result:
The output sequence y(n) of the system = [1 2 1 1 0 -1]
the input sequence of the system = [1 1 1 1]
the impulse response of the system is = 1 1 -1
the verified output sequence is 1 2 1 1 0 -1

Inference:
The impulse response h[n] is of finite duration.
The verified convolution output sequence is the same as the given y[n].

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

22
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Program 2
disp('Enter the sequences follows');
disp('Numerator coefficients: b=[b0 b1 b2 ...bn]');
disp('Denominator coefficients: a=[a0 a1 a2 ...an]');

## b=input('Enter the numerator coefficients');

a=input('Enter the denominator coefficients');
N=50;

h = impz(b,a,N);
disp('Impulse response is:');

n=0:1:N-1;
disp(h);
stem(n,h);
xlabel('n');
ylabel('h(n)');
grid on;
title('IMPULSE RESPONSE USING DIFFERENTIAL EQUATION');

Result:
Enter the sequences as follows
Numerator coefficients: b=[b0 b1 b2 ...bn]
Denominator coefficients: a=[a0 a1 a2 ...an]

## Enter the numerator coefficients[1]

Enter the denominator coefficients>> [1 -1 0.9]
Impulse response is:

## 1.0000, 1.0000, 0.1000, -0.8000, -0.8900, -0.1700, 0.6310, 0.7840, 0.2161

-0.4895, -0.6840, -0.2434, 0.3722, 0.5912, 0.2563, -0.2758, -0.5065, -0.2583
0.1976, 0.4300, 0.2522, -0.1348, -0.3618, -0.2405, 0.0852, 0.3016, 0.2249
-0.0465, -0.2489, -0.2071, 0.0169, 0.2033, 0.1881, 0.0051, -0.1642, -0.1688
-0.0210, 0.1309, 0.1498, 0.0320, -0.1028, -0.1316, -0.0391, 0.0794, 0.1145
0.0431, -0.0600, -0.0988, -0.0448, 0.0441

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

23
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Inference:
The impulse response h[n] is of infinite duration. h[n] is stable (as h[n] is absolutely
+∞
summable ∑ h[n] < ∞ , decaying exponential).
n = −∞

EXPERIMENT NO 3:

## Aim: To obtain convolution of two finite duration sequences.

Theory:
• The output y[n] of a LTI (linear time invariant) system can be obtained by convolving
the input x[n] with the system’s impulse response h[n].
+∞ +∞
• The convolution sum is y[n] = x[n] ∗ h[n] = ∑ x[k ]h[n − k ] =
k = −∞
∑ x[n − k ]h[k ]
k = −∞

## • x[n] and h[n] can be both finite or infinite duration sequences.

Even if one (or both) of the sequences is infinite (say, h[n] = (0.9 ) u[n] ), we can
n

analytically evaluate the convolution formula to get a functional form (closed form
solution) of y[n].
• If both the sequences are of finite duration, then we can use the MATLAB function
‘conv’ to evaluate the convolution sum to obtain the output y[n]. Convolution is
implemented as polynomial multiplication (refer MATLAB help).
• The length of y[n] = xlength + hlength -1.
• The conv function assumes that the two sequences begin at n=0 and is invoked by
y=conv(x,h).
• Even if one of the sequences begin at other values of n, say n=-3,or n=2; then we need
to provide a beginning and end point to y[n] which are ybegin=xbegin+hbegin and
yend=xend+hend respectively.
Algorithm:
1. Input the two sequences as x1, x2
2. Convolve both to get output y.
3. Plot the sequences.

MATLAB Implementation:
MATLAB recognizes index 1 to positive maximum. Index 0 is also not recognized. The
timing information for a sequence is provided by another vector, say n=-3:5; creates a
vector with values from -3 to 5 with an increment of 1.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

24
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

During plotting, the time vector size and the sequence size should be the same, i.e., the
number of elements in the sequence x1 and in its time vector n1 should be the same.
Similarly for x2 and y.

MATLAB Program:
% linear convolution
clear all; close all;
x=input('Enter the signal x(n)=')
h=input('Enter the impulse response sequence h(n)=')

lx=length(x);
lh=length(h);
len=lx+lh-1;
t=0:1:len-1;

for n=1:len
y(n)=0;
for k=1:lx
if((n-k)>=0&(n-k)<lh)
y(n)=y(n)+x(k).*h(n-k+1);
end
end
end

## % to dispaly the result.

disp('System response Output')
disp(y)

## % Compare the result with inbuilt function.

yc=conv(x,h);
disp('Convolution from inbuilt function')
disp(yc);
t1=0:1:lx-1; t2=0:1:lh-1;

% Plot
subplot(3,1,1), stem(t1,x); grid on;
ylabel('----> x(n)'); xlabel('-----------> n');
title('Linear Convolution of two sequences');

## subplot(3,1,2), stem(t2,h); grid on;

ylabel('----> h(n)'); xlabel('-----------> n');

## subplot(3,1,3), stem(t,y); grid on;

ylabel('----> y(n)'); xlabel('-----------> n');

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

25
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Result:
Enter the signal x(n)=[1 2 3 4]
x= 1 2 3 4

h= 1 1 1 1

## System response Output: 1 3 6 10 9 7 4

Convolution from inbuilt function: 1 3 6 10 9 7 4

Inferences: …………..

## Questions: 1. Write a program to compute the convolution of two sided sequences.

2. Write a program to compute the convolution using FT

## Autocorrelation of a given sequence and verification of its properties.

Aim: To obtain autocorrelation of the given sequence and verify its properties.

Theory:
• Correlation is mathematical technique which indicates whether 2 signals are related
and in a precise quantitative way how much they are related. A measure of similarity
between a pair of energy signals x[n] and y[n] is given by the cross correlation

sequence rxy[l] defined by rxy [l ] = ∑ x[n] y[n − l ]; l = 0,±1,±2,... .
n = −∞

• The parameter ‘l’ called ‘lag’ indicates the time shift between the pair.

• Autocorrelation sequence of x[n] is given by rxx [l ] = ∑ x[n]x[n − l ]; l = 0,±1,±2,...
n = −∞

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

26
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## o The autocorrelation sequence is an even function i.e., rxx [l ] = rxx [−l ]

o At zero lag, i.e., at l=0, the sample value of the autocorrelation sequence has
its maximum value (equal to the total energy of the signal εx) i.e.,

rxx [l ] ≤ rxx [0] = ε x = ∑x
n = −∞
2
[n] .

• This is verified in Fig. 5.1, where the autocorrelation of the rectangular pulse (square)
has a maximum value at l=0. All other samples are of lower value. Also the maximum
value = 11 = energy of the pulse [12+12+12..].
o A time shift of a signal does not change its autocorrelation sequence. For
example, let y[n]=x[n-k]; then ryy[l] = rxx[l] i.e., the autocorrelation of x[n] and
y[n] are the same regardless of the value of the time shift k. This can be
verified with a sine and cosine sequences of same amplitude and frequency
will have identical autocorrelation functions.
o For power signals the autocorrelation sequence is given by
k
1
rxx [l ] = lim
k →∞ 2k + 1
∑ x[n]x[n − l ]; l = 0,±1,±2,... and for periodic signals with
n=− k

N −1
1
period N it is rxx [l ] =
N
∑ x[n]x[n − l ]; l = 0,±1,±2,... and this rxx[l] is also
n =0

periodic with N. This is verified in Fig. 5.3 where we use the periodicity
property of the autocorrelation sequence to determine the period of the
periodic signal y[n] which is x[n] (=cos(0.25*pi*n)) corrupted by an additive
uniformly distributed random noise of amplitude in the range [-0.5 0.5]

Algorithm:
1. Input the sequence as x.
2. Use the ‘xcorr’ function to get auto correlated output r.
3. Plot the sequences.
MATLAB Implementation:
MATLAB has the inbuilt function XCORR(A), when A is a vector, is the auto-
correlation sequence. If A is of length M vector (M>1), then the xcorr function returns the
length 2*M-1 auto-correlation sequence. The zeroth lag of the output correlation is in the
middle of the sequence at element M.
XCORR(...,MAXLAG) computes the (auto/cross) correlation over the range of lags:
-MAXLAG to MAXLAG, i.e., 2*MAXLAG+1 lags. If missing, default is MAXLAG = M-1.
[C,LAGS] = XCORR(...) returns a vector of lag indices (LAGS).

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

27
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

MATLAB Programs

## %Energy signals %r = conv(x, fliplr(x));

r=xcorr(x);
%simple sequence disp('autocorrelation sequence r=');
x2=[3,-1,2,1]; disp(r);
>> xcorr(x2)
ans = 3 5 -3 15 -3 5 3 %plot the sequences
subplot(2,1,1)
%Computation of Autocorrelation of a stem(n,x);
% rectangular Sequence title('square sequence');
n = -5:5; subplot(2,1,2)
N=10; k = -N:N;
% Generate the square sequence stem(k, r);
x = ones(1,11); title('autocorrelation output');
% Compute the correlation sequence xlabel('Lag index'); ylabel('Amplitude');

Result:
The output plot is in Fig.5.1
autocorrelation sequence r = 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000
10.0000 11.0000 10.0000 9.0000 8.0000 7.0000 6.0000 5.0000 4.0000 3.0000 2.0000 1.0000

Inference: Following Autocorr properties are verified 1) Max peak of 11 (=energy of the pulse) at zero lag (l=0)
2)the autocorr seq is an even function

Fig.5.2

Fig. 5.3

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

28
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Inference 2: The plot of noise corrupted signal y[n] (Fig. 5.3) does not show any noticeable
periodicity, but its autocorrelation sequence has distinct peaks at lags that are multiples of
8,indicating thaty[n] is a periodic with N=8 (cos(0.25*pi*n)=cos(wn) implies w=2*pi*f; N=
1/f = 2/0.25 =8). Also notice the strong peak at zero lag.

From Fig.5.2, the autocorrelation of the noise component has a very strong peak only at zero
lag. The amplitudes are considerably smaller at other values of the lag as the sample values
(of noise generated by rand function) are uncorrelated with each other.

## Cross correlation of a given sequence and verification of its properties.

Aim: To obtain cross correlation of the given sequence and verify its properties.

Theory:
• Cross Correlation has been introduced in the last experiment. Comparing the
equations for the linear convolution and cross correlation we find that
∞ ∞
rxy [l ] = ∑ x[n] y[n − l ] =
n = −∞
∑ x[n] y[−(l − n)] = x[l ] ∗ y[−l ] . i.e., convolving the
n = −∞

reference signal with a folded version of sequence to be shifted (y[n]) results in cross
correlation output. (Use ‘fliplr’ function for folding the sequence for correlation).
• The properties of cross correlation are 1) the cross correlation sequence sample values
are upper bounded by the inequality rxx [l ] ≤ rxx [0]ryy [0] = ε x ε y

2) The cross correlation of two sequences x[n] and y[n]=x[n-k] shows a peak at the
value of k. Hence cross correlation is employed to compute the exact value of the
delay k between the 2 signals. Used in radar and sonar applications, where the
received signal reflected from the target is the delayed version of the transmitted
signal (measure delay to determine the distance of the target).
3) The ordering of the subscripts xy specifies that x[n] is the reference sequence that
remains fixed in time, whereas the sequence y[n] is shifted w.r.t x[n]. If y[n] is the
reference sequence then ryx [l ] = rxy [−l ] . Hence ryx[l] is obtained by time reversing the

sequence rxy[l].

Program:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

29
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## %Verification of the properties

%Small MATLAB code
xi=[1,2,3,-1,0,0];
x2=[0,0,1,2,3,-1]; %=xr[n-2],i.e., k=2
>> xcorr(xi,x2)
ans = {−1,1,5,15,5, 1,−1,0,0,0,0}

Inference: Strong peak of 15 at lag = -2 implies the delay between xi and x2 is 2.
Also peak =15=energy of xi (1+22+32+(-1)2) implies that both xi and x2 are strongly correlated.

## %consider the below sequences

xr=[1,2,3,-1];
x2=[3,-1,1,2];
xcorr(xr,x2) ans = {2,5,7, 2,2,10,−3}

## xcorr(x2,xr) ans = {−3,10,2, 2,7,5,2}

Inference: Strong peak of 10 at lag = 2 implies the delay between xr and x2 is 2, but since 10<15, it
implies that xr and x2 are uncorrelated slightly (may be due to noise,etc). ryx [l ] = rxy [−l ] is verified.

Algorithm:
1. Input the sequence as x and y.
2. Use the ‘xcorr’ function to get cross correlated output r.
3. Plot the sequences.
MATLAB Implementation:
MATLAB has the inbuilt function XCORR: Say C = XCORR(A,B), where A and B are
length M vectors (M>1), returns the length 2*M-1 cross-correlation sequence C. If A and B
are of different length, the shortest one is zero-padded. Using convolution to implement
correlation, the instruction is FLIPLR Flip matrix in left/right direction. FLIPLR(X)
returns X with row preserved and columns flipped in the left/right direction. X = 1 2 3
becomes 3 2 1.
MATLAB Program:

## % Computation of Cross-correlation Sequence using folded sequence and convolution

x = input('Type in the reference sequence = '); x = input('Type in the reference sequence = ');
y = input('Type in the second sequence = '); y = input('Type in the second sequence = ');

## % Compute the correlation sequence % Compute the correlation sequence

n1 = length(y)-1; n1 = length(y)-1;
n2 = length(x)-1; n2 = length(x)-1;
r = conv(x,fliplr(y)); r = xcorr(x,y);
%[r,lag]=xcorr(x,y);
disp(‘Cross correlation output is =’);
disp(r); disp('Cross correlation output is =');
k = (-n1):n2; %time vector for plotting disp(r);
stem(k,r); N=max(n1,n2) ;
xlabel('Lag index'); ylabel('Amplitude'); k = (-N):N;
stem(k,r); %stem(lag,r);
% Computation of Cross-correlation Sequence xlabel('Lag index'); ylabel('Amplitude');
%using xcorr function

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

30
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Result:
Type in the reference sequence = [1 3 -2 1 2 -1 4 4 2]
Type in the second sequence = [2 -1 4 1 -2 3]
Cross correlation output is = 3 7 -11 14 13 -15 28 6 -2 21 12 12 6 4

## Verification: with xcorr(x,y), the output is

{-0.0000 , -0.0000 , 0.0000, 3.0000, 7.0000, -11.0000, 14.0000, 13.0000, -15.0000, 28.0000, 6.0000, -2.0000,
21.0000, 12.0000, 12.0000, 6.0000 , 4.0000}

Note: For sequences with different lengths, the length of the output using xcorr is 2*max(n1,n2)-1 = 2* 9-1=17
whereas using conv program, the length of output is n1+n2-1.

Fig.6.1 Cross correlation output Fig.6.2 Cross correlation output using xcorr
using Convolution

FREQUENCY RESPONSE:
The frequency response is a representation of the system's response to sinusoidal inputs at varying
frequencies. The output of a linear system to a sinusoidal input is a sinusoid of the same frequency but with
a different magnitude and phase. Any linear system can be completely described by how it changes the
amplitude and phase of cosine waves passing through it. This information is called the system's frequency
response.Since both the impulse response and the frequency response contain complete information about
the system, there must be a one-to-one correspondence between the two. Given one, you can calculate the
other.The relationship between the impulse response and the frequency response is one of the foundations of
signal processing:A system's frequency response is the Fourier Transform of its impulse response Since h [ ]
is the common symbol for the impulse response, H [ ] is used for the frequency response.

## Discrete Time Fourier Transform:

The discrete-time Fourier transform (DTFT) X(ejω) of a sequence x[n] is defined

In general X(ejω) is a complex function of the real variable ω and can be written as

where Xre(ejω) and Xim(ejω) are, respectively, the real and imaginary parts of X(ejω), and are real
functions of ω. X(ejω) can alternately be expressed in the form

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

31
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The quantity |X(ejω)| is called the magnitude function and the quantity θ(ω) is called the phase
function
In many applications, the Fourier transform is called the Fourier spectrum and, likewise, |X(ejω)|
and θ(ω) are referred to as the magnitude spectrum and phase spectrum, respectively.

The DTFT X(ejω) is a periodic continuous function in ω with a period 2π. The DTFT satisfies a
number of useful properties that are often uitilized in a number of applications.

MATLAB COMMANDS:

For complex Z, the magnitude R and phase angle theta are given by:
R = abs (Z)
Theta = angle (Z)

Y = fft(X) returns the discrete Fourier transform of vector X, computed with a fast Fourier
transform (FFT) algorithm.
Y = fft(X)
Y = fft(X,n) returns the n-point FFT.
Y = fft(X, n)
01:

Compute the discrete Fourier transform of the following function analytically and Then plot the magnitude
and phase:

## Its DTFT is given as:

MATLAB Code:

w = [0:500]*pi/500;
z = exp(-j*w);
x = 3*(1-0.9*z).^(-1);
a = abs(x);
b = angle(x)*180/pi;
subplot(2,1,1);
plot(w/pi,a);
subplot(2,1,2);
plot(w/pi,b);

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

32
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

OUTPUT:

num=[2 1]
den=[1 –0.6]

## • Plot real and imaginary parts of Fourier spectrum.

• Also plot the magnitude and phase spectrum.

MATLAB CODE:
% Evaluation of the DTFT title('Imaginary part of H(e^{j\omega})')
clc; xlabel('\omega /\pi');
% Compute the frequency samples of the ylabel('Amplitude');
DTFT subplot(2,2,3)
w = -4*pi:8*pi/511:4*pi; plot(w/pi,abs(h));
num = [2 1]; grid on;
den = [1 -0.6]; title('Magnitude Spectrum |H(e^{j\omega})|')
h = freqz(num, den, w); xlabel('\omega /\pi');
% Plot the DTFT ylabel('Amplitude');
subplot(2,2,1) subplot(2,2,4)
plot(w/pi,real(h)); plot(w/pi,angle(h));
grid on; grid on;
title('Real part of H(e^{j\omega})') title('Phase Spectrum arg[H(e^{j\omega})]')
xlabel('\omega /\pi'); xlabel('\omega /\pi');
subplot(2,2,2)
plot(w/pi,imag(h));
grid on;

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

33
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

OUTPUT

## Fast Fourier Transform:

The Fast Fourier Transform (FFT) is just a computationally fast way to calculate the DFT.

03:
Determine the Fourier transform of the following sequence. Use the FFT (Fast Fourier
Transform) function.
x (n) = {4 6 2 1 7 4 8}

MATLAB Code:

n = 0:6; grid on
x = [4 6 2 1 7 4 8]; title('Magnitude Response');
a = fft(x); subplot(2,1,2);
mag = abs(a); plot(pha);
pha = angle(a); grid on
subplot(2,1,1); title('phase Response');
plot(mag);

OUTPUT:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

34
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## If ‘x[n]’ be the sequence ,and X(ejw) be its fourier transform then,

x[n]Å----F-----ÆX(ejw)

then, for the time-shifted sequences, a simple transformation of the index of summation in
the discrete-time Fourier transform yields

x[n-nd]Å----F-----Æe-jwndX(ejw)

## #04: Observe the time-shifting property of DTFT.

• Plot and compare the magnitude spectrum of the original input with time delayed input.
• Plot and compare the phase spectrum of the original input with delayed input.

MATLAB CODE:

## % Time-Shifting Properties of DTFT

clc;
w = -pi:2*pi/255:pi;
D = 10;
num = [1 2 3 4 5 6 7 8 9];
h1 = freqz(num, 1, w);
h2 = freqz([zeros(1,D) num], 1, w);
subplot(2,2,1)
plot(w/pi,abs(h1));
grid on;
title('Magnitude Spectrum of Original Sequence')
subplot(2,2,2)
plot(w/pi,abs(h2));
grid on;
title('Magnitude Spectrum of Time-Shifted Sequence')
subplot(2,2,3)
plot(w/pi,angle(h1));
grid on;
title('Phase Spectrum of Original Sequence')
subplot(2,2,4)
plot(w/pi,angle(h2));
grid on;
title('Phase Spectrum of Time-Shifted Sequence')

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

35
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## #05: Observe the frequency shifting property of DTFT.

• Plot and compare the magnitude spectrum of the original input with frequency shifted
input.
• Plot and compare the phase spectrum of the original input with frequency shifted input..

MATLAB CODE:

## % Frequency-Shifting Properties of DTFT

clc;
w = -pi:2*pi/255:pi;
wo = 0.4*pi;
num1 = [1 3 5 7 9 11 13 15 17];
L = length(num1);
h1 = freqz(num1, 1, w);
n = 0:L-1;
num2 = exp(wo*i*n).*num1;
h2 = freqz(num2, 1, w);
subplot(2,2,1); plot(w/pi,abs(h1));
grid on;
title('Magnitude Spectrum of Original Sequence')
subplot(2,2,2)
plot(w/pi,abs(h2));
grid on;
title('Magnitude Spectrum of Frequency-Shifted Sequence')
subplot(2,2,3)
plot(w/pi,angle(h1));
grid on;
title('Phase Spectrum of Original Sequence')
subplot(2,2,4)
plot(w/pi,angle(h2));
grid on;
title('Phase Spectrum of Frequency-Shifted Sequence')

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

36
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

OUTPUT

Questions:
1. Determine the Fourier transform of the following sequence. Use the FFT (Fast Fourier
Transform) function,
x(n) = {4 3 2 1 1 2 3 4}

2. Compute the discrete Fourier transform of the following function analytically and then
Plot the magnitude and phase
x(n) = 2(0.8)n+2 u(n-2)

3. Determine H(w) and plot its magnitude and phase for the following system.

H(ejw) = 1+e-jw
1-e-jw+0.9e-j2w

## a) Write a MATLAB code that manually implements the above system.

b) Compare with the spectrum obtained from freqz command
• Plot the magnitude and frequency spectrum.
• Also plot real and imaginary plots

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

37
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## Z-transform and Inverse Z-transform Analysis

Objective: To study the Z-transform and Inverse Z-transform practically using MATLAB.

Description: In mathematics and signal processing, the Z-transform converts a discrete time-
domain signal, which is a sequence of real or complex numbers, into a complex frequency-domain
representation.

The Z-transform, like many other integral transforms, can be defined as either a one-sided or two-
sided transform.

## Bilateral Z-transform: The bilateral or two-sided Z-transform of a discrete-time signal x[n] is

the function X(z) defined as

Unilateral Z-transform : Alternatively, in cases where x[n] is defined only for n ≥ 0, the
single-sided or unilateral Z-transform is defined as

## In signal processing, this definition is used when the signal is causal.

As analog filters are designed using the Laplace transform, recursive digital filters are developed
with a parallel technique called the z-transform. The overall strategy of these two transforms is the
same: probe the impulse response with sinusoids and exponentials to find the system's poles and
zeros. The Laplace transforms deals with differential equations, the s-domain, and the s-plane.
Correspondingly, the z-transform deals with difference equations, the z-domain, and the z-plane.
However, the two techniques are not a mirror image of each other; the s-plane is arranged in a
rectangular coordinate system, while the z-plane uses a polar format. Recursive digital filters are
often designed by starting with one of the classic analog filters, such as the Butterworth,
Chebyshev, or elliptic. A series of mathematical conversions are then used to obtain the desired
digital filter. The Z transform of a discrete time system X[n] is defined as Power Series.

## Rational Z-transform to factored Z-transform:

Example:
Let the given transfer function be in the rational form,
2z4+16z3+44z2+56z+32
G(z)= --------------------------------
3z4+3z3-15z2+18z-12
It is required to convert it into factored form, so that we can find the poles and zeros
mathematically by applying quadratic equation.
Matlab command required for converting rational form to factored form be

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

38
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

‘Zp2sos’
The factored form of G(z) as evaluated by ‘zp2sos’ be,

G(z)= ( 0.6667 + 0.4z-1 + 0.5333 z-2) (1.000 + 2.000 z-1 +2.000 z-2)
(1.000 + 2.000z-1 -4.000z-2 )(1.000 - 1.000 z-1 + 1.000 z-2)

## Factored Z-transform / zeros,poles to rational Z-transform:

It is the inverse of the above case, when the transfer function is given in factored form and it is
required to convert in rational form then a single ‘matlab’ command can serve the purpose.
Example:
Lets use the above result i-e;transfer function in factored for,

G(z)=( 0.6667 + 0.4z-1 + 0.5333 z-2) (1.000 + 2.000 z-1 +2.000 z-2)
(1.000 + 2.000z-1 -4.000z-2 )(1.000 - 1.000 z-1 + 1.000 z-2)

For building up transfer function in rational form we find the poles and zeros of above system
simply by using matlab ‘root’ command or by hand. Or simply we have poles and zeros of the
given system we can find the transfer function in factored form.

Matlab command that converts poles and zeros of the system in to transfer function is ‘zp2tf’ .

## Rational Z-transform to partial fraction form:

This technique is usually used , while taking the inverse Z-transform and when the order ‘H(z)’ is
high so that it is quite difficult to solve it mathematically.
Example:
Consider the transfer function in the rational form i-e;
18z3
G(z)= ------------------
18z3+3z2-4z-1
We can evaluate the partial fraction form of the above system using matlab command. The partial
fraction form be,
G(z)= 0.36__ + __0.24__ + _0.4____
1 – 0.5z-1 1+0.33 z-1 (1+0.33 z-1)

Matlab command that converts rational z-transform in to partial fraction form is ‘residuez’.

## Partial fraction form to Z-transform:

This technique is used when it is required to convert partial fraction expression in to rational Z-
transform.
Example: Take the partial fraction form of above ,
G(z)= 0.36__ + __0.24__ + _0.4____
1 – 0.5z-1 1+0.33 z-1 (1+0.33 z-1)

Matlab command that converts partial fraction form into rational z-transform is
‘residuez’

## Zplane: Zero-pole plot

zplane(b,a)
This function displays the poles and zeros of discrete-time systems.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

39
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Pole Zero Diagrams For A Function In Z Domain: Z plane command computes and display the
pole-zero diagram of Z function. The Command is Zplane(b,a)
To display the pole value, use root(a)
To display the zero value, use root(b)

Matlab Code:
b=[0 1 1 ]
a= [1 -2 +3]
roots(a)
roots(b)
zplane(b,a);

ans =
1.0000 + 1.4142i
1.0000 - 1.4142i

ans= -1

Frequency Response:
The Freqz function computes and display the frequency response of given Z- Transform
of the function freqz(b,a,Fs)
b= Coeff. Of Numerator, a= Coeff. Of Denominator, Fs= Sampling Frequency
Matlab Code:
b=[2 5 9 5 3]
a= [5 45 2 1 1]
freqz(b,a);

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

40
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Example:

Plot the magnitude and phase of the frequency response of the given digital filter Using freqz function:
y(n) = 0.2x(n) + 0.52y(n-1) – 0.68(y(n-2)

Matlab Code:

b = [0.2];
a= [1, -0.52, 0.68];
w = [0:1:500]*pi/500;
H=freqz(b,a,w);
magH = abs(H);
phaH = angle(H)*180/pi;
subplot(2,1,1);
plot(w/pi,magH);
title('Magnitude Response');
xlabel('frequency in pi units');
ylabel('│H│');
subplot(2,1,2);
plot(w/pi,phaH);
title('Phase Response');
xlabel('frequency in pi units');
ylabel('Degrees');

Example:
Assume we have a transfer function in the z-domain given by

z −1 z
X (z ) = −1 −2
= 2 .
1 − 0.25 z − 0.375 z z − 0.25 z − 0.375

## Factoring this, it’s partial fraction expansion can be found to be

z c1 z c2 z 0.8 z − 0.8 z
X (z ) = = + = + .
(z − 0.75)(z + 0.5) (z − 0.75) (z + 0.5) (z − 0.75) (z + 0.5)
The inverse z-transform of this is thus

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

41
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

x (n ) = [(0 . 8 )(0 . 75 ) n
]
+ (− 0 . 8 )(− 0 . 5 ) u (n )
n

There are several MATLAB functions that could assist with calculating and analyzing these results.
We can find the roots of the denominator polynomial using
>> den = [1 -0.25 -0.375];
>> roots(den)
ans =
0.7500
-0.5000

## We can then plot the zeros and poles either with

(1) zeros and poles in column vectors

>> z = [0]
z= 0
>> p = [0.75; -0.5]
p=
0.7500
-0.5000
>> zplane(z,p)

## numerator and denominator coefficients in row vectors

>> num = [0 1 0]
num =
0 1 0
>> den = [1 -0.25 -0.375]
den =
1.0000 -0.2500 -0.3750
>> zplane(num,den)
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

We can find the impulse response (or inverse z-transform) of the polynomial based on the power
series expansion method using the “impz” function

## h = impz(num,den,N) where N is the number of terms or coefficients to compute

>> h = impz(num,den,10)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

42
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

h=
0
1.0000
0.2500
0.4375
0.2031
0.2148
0.1299
0.1130
0.0770
0.0616

## Assume you have a polynomial of the form

B( z ) b0 + b1 z −1 + b2 z −2 + L + bM z − M
( )
H z = =
A( z ) a 0 + a1 z −1 + a 2 z − 2 + L + a N z − N

## This can be turned into a partial fraction expansion of the form

B(z ) R1 R2 R3 Rn
= + + +L+ +K
A( z ) 1 − p1 z −1
1 − p2 z −1
1 − p3 z −1
1 − p n z −1
B(z ) Rz R z Rz R z
= 1 + 2 + 3 +L+ n + K
A( z ) z − p1 z − p 2 z − p3 z − pn

where we can get the residues (coefficients), poles, and direct terms.

## Thus for our example we have

z z −1
X (z ) = 2 =
z − 0.25 z − 0.375 1 − 0.25 z −1 − 0.375 z − 2
so in MATLAB we would enter

## >> num = [0 1];

>> den = [1 -0.25 -0.375];
>> [R,P,K]=residuez(num,den)

R=
0.8000
-0.8000

P=
0.7500
-0.5000

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

43
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

K=
[]

## which corresponds to a partial fraction expansion of

0.8 z − 0.8 z
X (z ) = + +0
z − 0.75 z + 0.5
[
x(n ) = (0.8)(0.75) + (− 0.8)(− 0.5) u (n )
n n
]

We can also plot the frequency response of a particular polynomial with freqz

z
For X (z ) = we would enter
z − 0.25 z − 0.375
2

## >> num = [0 1 0];

>> den = [1 -0.25 -0.375];
>> freqz(num, den, 512)
10
agnitude(dB)

0
M

-5
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency (×π rad/sample)

0
Phase(degrees)

-50

-100

-150

-200
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency (×π rad/sample)

## Here we have used the form

freqz(num,den,N)
where ‘num’ are the numerator coefficients, ‘den’ are the denominator coefficients, and ‘N’ is the
number of points to use in the plot which goes from 0 to π. An alternative form is to use

[H,f] = freqz(num,den,N,Fs)
plot(f, abs(H))

‘num’ and ‘den’ are the same. ‘Fs’ is the sampling frequency. ‘N’ values between 0 and Fs are
calculated. The response data versus frequency are stored in H.
>> num = [0 1 0];
>> den = [1 -0.25 -0.375];

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

44
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## >> [H,f] = freqz(num,den,512,8000);

>> plot(f,abs(H))

2.5

1.5

0.5
0 500 1000 1500 2000 2500 3000 3500 4000

Question:

Task#1: Express the following z-transform in factored form , plot its poles and zeros,and then
determine its ROCs.
2z4+16z3+44z2+56z+32
G(z)= --------------------------------
3z4+3z3-15z2+18z-12
Task#2: Determine the partial fraction expansion of the z-transform G(z) given by

18z3
G(z)= ------------------
18z3+3z2-4z-1

LAPLACE TRANSFORMS
You can compute Laplace transform using the symbolic toolbox of MATLAB. MATLAB forms
Laplace transform symbolically. Thus, you need to first define the variable t as a "symbol".

SYMS Command

Whenever you want to use symbolic mathematics, you must use the syms operator to alert
MATLAB that you are using a symbolic variable, and that it does not have a specific value
Example 1.

Solution:
>> syms t
>> f=5*exp(-2*t);

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

45
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

>> L=laplace(f)

L=
5/(s+2)

>> ilaplace(1/s-2/(s+4)+1/(s+5))

Matlab result:

Ans : =

1-2*exp(-4*t)+exp(-5*t)

Examples:
1. You can compute Laplace transform using the symbolic toolbox of MATLAB. If you
want to compute the Laplace ace transform of x(t) = t , you can use the following MATLAB
program.
>> f=t;
>> syms f t
>> f=t;
>> laplace(f)
ans =1/s^2
where f and t are the symbolic variables, f the function, t the time variable.

2. The inverse transform can also be computed using MATLAB. If you want to compute
the inverse Laplace transform of

## You can use the following command lines.

>> syms F S
>> F=24/(s*(s+8));
>> ilaplace(F)
ans = 3-3*exp(-8*t)

3. We can also do inverse Laplace transform using partial fraction expansion, and
MATLAB can help you with that. If you want to find the partial-fraction expansion of

## the following MATLAB program gives you the coefficients in

the expansion. You write the coefficients of the numerator and the denominator in separate vectors
and MATLAB gives you the coefficients with the corresponding poles in the expansion.

## >> n=[0 0 4 4 4];

>> d=[1 3 2 0 0];
>> [r,p,k]=residue(n,d)

46
r=
-3
4
-1
2
p=
-2
-1
0
0

## Therefore, the partial fraction expansion is:

Calculating the Laplace F(s) transform of a function f(t) is quite simple in Matlab. First you need
to specify that the variable t and s are symbolic ones. This is done with the command
>> syms t s
Next you define the function f(t). The actual command to calculate the transform is
>> F=laplace(f,t,s)
To make the expression more readable one can use the commands, simplify and pretty.
here is an example for the function f(t),

>> syms t s
>> f=-1.25+3.5*t*exp(-2*t)+1.25*exp(-2*t);
>> F=laplace(f,t,s)
F =
-5/4/s+7/2/(s+2)^2+5/4/(s+2)
>> simplify(F)
ans =
(s-5)/s/(s+2)^2
>> pretty(ans)
s - 5
----------
s (s + 2)2
which corresponds to F(s),

Alternatively, one can write the function f(t) directly as part of the laplace command:
>>F2=laplace(-1.25+3.5*t*exp(-2*t)+1.25*exp(-2*t))

## Inverse Laplace Transform

The command one uses now is ilaplace. One also needs to define the symbols t and s.
Lets calculate the inverse of the previous function F(s),

>> syms t s
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

>> F=(s-5)/(s*(s+2)^2);
>> ilaplace(F)
ans =
-5/4+(7/2*t+5/4)*exp(-2*t)
>> simplify(ans)
ans =
-5/4+7/2*t*exp(-2*t)+5/4*exp(-2*t)
>> pretty(ans)
- 5/4 + 7/2 t exp(-2 t) + 5/4 exp(-2 t)
Which corresponds to f(t)

## Alternatively one can write

>> ilaplace((s-5)/(s*(s+2)^2))
Here is another example.

>> F=10*(s+2)/(s*(s^2+4*s+5));
>> ilaplace(F)
ans =
-4*exp(-2*t)*cos(t)+2*exp(-2*t)*sin(t)+4
Which gives f(t),

## making use of the trigonometric relationship,

Matlab often gives the inverse Laplace Transform in terms of sinhx and coshx. Using the
following definition one can rewrite the hyperbolic expression as a function of exponentials:

Also, you may find the “Heaviside(t) function which corresponds to the unit step function u(t):
thus the function H(t) = heaviside(t) =0 for t<0 and H(t) = heaviside(t)=1 for t>0.

As an example, suppose that Matlab gives you the following result for the inverse Laplace
transform:
2 heaviside(t-10) exp(-5/2t+25) sinh(1/2t-5)
This can be re-written, using the definition of the sinh(x) function:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

48
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

This last expression is closer to what your hand calculations will give you for the inverse Laplace
Transform.

• To begin your SIMULINK session open first MATLAB ICON by clicking mouse twice and
then type
You will now see the Simulink block library.

• Browse through block libraries. E.g., if you click Continuous, you will see the following:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

49
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

1
Observe the description of the integrator beside the block that will be used for integrator, . This
s
operator notation comes from linear systems domain, where s is Laplace variable. Roughly, s
d 1
corresponds to derivative operator, , and its inverse , to integration, .
dt s z
• Math Operations library is shown below

After browsing through other block libraries, we are now ready to start generating a simple
• Choose in menu selection File, then New and Model. This file will be called untitled.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

50
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Untitled file, where the SIMULINK configuration is constructed using different blocks
in the library. With a mouse you can configure your model
into the empty space.

EXAMPLE 1: Input signal is sin t . It is fed into an amplifier with gain 2. Simulate the output of
the amplifier.

Solution: Pick first the amplifier. This you can find under Math and it is called Gain. Move the
cursor on top of Gain, keep it down and move the Gain block to untitled file and release it. If you
fail, try again. The result is shown below.

The gain has only one parameter, which has value of 1. You can change it by moving the cursor close to 1
and clicking once and then operating as you would with any word processing system. Once finished, click
OK. The numerical value inside the block will now change to 2. Next find the input signal block. This is
under Sources and is called Sine Wave. Again move the cursor on top of it, keep pressing the mouse while
you move the block to the untitled file and then release the mouse. In order to see the result, you need to
install a sink from Sinks library. In the beginning, the easiest sink to use is scope. Move that block in the
same way as the others to the untitled file. The result is shown below.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

51
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The only thing missing of the system is to connect the peaces together. This is done with the
mouse. Take the cursor to the output of Sine Wave block. You’ll see a hairline cursor, when you
are close enough. Now press the mouse down. Keep it down and move it close to the input of
gain. You’ll see a line forming, while you drag your mouse. Once you reach the input another
hairline cursor can be seen and you can release the mouse.

Your simulation system is now complete. Before simulation you should check that the parameter
values in the Sine Wave block are correct. Open it by placing the cursor on top and click twice.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

52
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

For this example Amplitude is 1 and frequency (rad/s) is also 1, so default values are OK. There is
no phase shift and sampling is not issue here.

You can begin simulation by choosing Start simulation from Simulation menu or by clicking the
start button.

Start button

## EXERCISE 2: Solve the differential equation

dx
= − 2 x + 1, t > 0 .
dt
x (0 ) = 0 .

Note: The input is 1 after t> 0. This can be taken as a step function from the Sources block
library. Note however, that the stepping time is not t=0 but t=1.

Solution: If you are inexperienced with differential equations, you can use differential operator D.
d
Let D = . Then the differential equation becomes
dt

Dx = −2 x +1 (1)
or
Dx + 2 x = ( D + 2) x = 1 .

## This further leads to

NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
53
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

1
x= (2)
D+2

You can use either (1) or (2) for SIMULINK configuration. We will use the first one:
Dx = −2 x + 1 .
1
Laplace transform operator s is almost the same as D, except for the initial conditions. In SIMULINK
s
dx
means integration (see the block below). Input to the integrator is Dx = and output x. Thus in
dt
configuration you set up the right hand side and connect the everything to the input of the integrator.

The solution is found by choosing under Simulation menu Start simulation or by clicking Start
button.

The result is shown above. If you study the equation and the result, it is clear (why?) that we have made a
mistake in configuration. The sign in summation is wrong. Correct it as shown below. Now the result
corresponds to our expectations (if any).

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

54
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

If you want to see both the input and output at the same time, use Mux (multiplexer) block, which
you can find under Signals and Systems block library. Set up the system as shown below.

Double-click

Initial condition

As seen above you can change the initial value to e.g. –3.

The default time for simulation is 10. If you wish to simulate longer you have to change it. To do that open
Simulation menu and choose Simulation parameters.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

55
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## You can change the Stop time according to your needs.

Complete the exercise. Run the simulation from SIMULINK and also from Command window.

## DAMPED OSCILLATOR : Solve the damped oscillator problem

d 2x dx
2
+ 5 + 9 x = u (t )
dt dt

## dx Assume that u(t) = 0, that is, there is no input.

= x& (0) = −2
dt
x(0) = 2

PURPOSE: To illustrate how to configure a SIMULINK diagram for a higher order differential
equation and how to introduce initial conditions into it.

SOLUTION: Solve equation first with respect to the highest order derivative to obtain

d2x dx
2
= −5 − 9 x
dt dt

## To set up the right-hand side two integrators are needed:

d 2x dx
The input to the first integraror is the second derivative 2 and its output is . The latter is the innput to the
dt dt
second integrator producing x(t) at its output. In this way we have constructed the left-hand side of the equation.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

56
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

d 2x
Since the second derivative is equal to the right hand side, we collect it term by term. In order to do that we
dt 2
dx
need from the output of the first integrator, x(t) from the output of the second integrator and u(t), the step input
dt
must be generated. Here x(t) must also be multiplied by 9, so a gain is required. All these items are to be summed up
so a sum block is also needed. The final configuration is given below. The initial values are added to the integrators.
The resulting configuration is given below.

Next, set up the initial conditions by clicking the integrators one at a time and making appropriate
changes.

dx
The solution x(t) and are shown in Fig. below. The first figure is SIMULINK scope and the
dt
second is the result from Command window simulation.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

57
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The sharpness of the lower curve around t = 0.4 s is not real, it should be smooth. First you might
suspect numerical difficulties (there are none) due to too large a step size. This is not the case. It is
due to display graphics, i.e., not enough points have been saved to have a smooth presentation.
dx
The damping factor can be changed by changing the coefficient 5 in front of . If the coefficient
dt
is zero (no damping), the result is a sinusoidal. Increasing the damping will result in damping
oscillations. Complete the study to obtain the following responses.

Let us also plot a phase plane plot (x vs dx/dt). Note that here time has been eliminated. To see
the effect better, start with less damping. Change the coefficient 5 to 1.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

58
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

XY Graph does not adjust the scales automatically. In order to see the whole picture, click the XY
Graph open and adjust the scales. Adjusting also the Sample time results in smooth picture.

## CONCLUSION: A stable system. It converges towards the origin. Physical interpretation: In

origin both position and velocity are zero.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

59
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

REVIEW:
1. Finding the roots of a polynomial using ‘roots’
»a=[1 10 35 50 24];
»r=roots(a)
r=
-4.0000 -3.0000 -2.0000 -1.0000

## 2. Multiplying Polynomials using ‘conv’

»a=[1 2 1];b=[1 4 3];
»c=conv(a,b)
c=
1 6 12 10 3

3. Adding Polynomials. Only polynomials with the same length can be added together.

m=length(x);n=length(y);
if m>=n
z=x+[zeros(1,m-n),y];
else
z=y+[zeros(1,n-m),x];
end

## 4. Evaluating Polynomials using ‘polyval’

»a=[1 2 1];
»polyval(a,[1:3])
ans = 4 9 16

5. For typical systems the transfer function can be expressed as a rational function, such as
B( s) s2 +1 s2 +1
H ( s) = = = 3
A( s ) ( s + 1)( s + 2)( s + 3) s + 6 s 2 + 11s + 6
6. Partial Fraction Expansion using ‘residue’
»b=[1 0 1]; % B(s)
»a=[1 6 11 6]; % A(s)
»[gamma,alpha,k]=residue(b,a)

gamma =
5.0000
-5.0000
1.0000
alpha =
-3.0000
-2.0000
-1.0000

k = []

7. Inverse Laplace Transform using ‘ilaplace’ (this was not introduced in EE 311)

» syms F s
» F=(s^2+1)/(s^3+6*s^2+11*s+6);
»ilaplace(F)
ans = 5*exp(-3*t)-5*exp(-2*t)+exp(-t)

## 8. Plotting Complex Frequency Response of H(s) using ‘freqs’

» b=[1 0 1];
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
60
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

» a=[1 6 11 6];
» freqs(b,a)
% The output of this is seen in Figure One below.

0
10

Magnitude
-2
10

-4
10
0 1
10 10
F re q u e n c y (ra d / s )

100

50
Phase (degrees)

-5 0

-1 0 0
0 1
10 10
F re q u e n c y (ra d / s )

## Figure One Output of ‘freqs’

9. Create Bode Diagrams using ‘bode’ (frequency response with dB magnitude plot)

## » sys=tf([1 0 1],[1 6 11 6]);

» bode(sys)
% This is shown in Figure Two below.

B o d e D i a g ra m
0

-5 0
Magnitude (dB)

-1 0 0

-1 5 0

-2 0 0
9 0

4 5
Phase (deg)

-4 5

-9 0
-1 0 1 2
1 0 1 0 1 0 1 0
F re q u e n c y (ra d / se c )

Figure Two Bode plot of the same system from Figure One

SIMULINK model : Now we wish to use SIMULINK to simulate the system, e.g., see the output when the input is a
step function (see the Figure Three below). SIMULINK is a powerful simulation tool provided by MATLAB. It
allows for analysis/simulation of interconnections of dynamic systems (both continuous-time and discrete-time).

s2 +1
s3 +6s2 +11s+6
Step T ransfer Fcn S co p e

si m out

T o Workspace

Figure Three SIMULINK diagram for the step response of the system used in Figures One and Two

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

61
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Root Locus
Closed-Loop Poles

The root locus of an (open-loop) transfer function H(s) is a plot of the locations (locus) of all
possible closed loop poles with proportional gain k and unity feedback:

Y ( s) KH ( s )
The closed-loop transfer function is: =
R( s ) 1 + KH ( s )
and thus the poles of the closed loop system are values of s such that 1 + K H(s) = 0.

## If we write H(s) = b(s)/a(s), then this equation has the form:

Let n = order of a(s) and m = order of b(s) [the order of a polynomial is the highest power of s that
appears in it].

We will consider all positive values of k. In the limit as k -> 0, the poles of the closed-loop system
are a(s) = 0 or the poles of H(s). In the limit as k -> infinity, the poles of the closed-loop system
are b(s) = 0 or the zeros of H(s).

No matter what we pick k to be, the closed-loop system must always have n poles, where n is
the number of poles of H(s). The root locus must have n branches, each branch starts at a pole
of H(s) and goes to a zero of H(s). If H(s) has more poles than zeros (as is often the case), m < n
and we say that H(s) has zeros at infinity. In this case, the limit of H(s) as s -> infinity is zero.
The number of zeros at infinity is n-m, the number of poles minus the number of zeros, and is the
number of branches of the root locus that go to infinity (asymptotes).

Since the root locus is actually the locations of all possible closed loop poles, from the root locus
we can select a gain such that our closed-loop system will perform the way we want. If any of the
selected poles are on the right half plane, the closed-loop system will be unstable. The poles that
are closest to the imaginary axis have the greatest influence on the closed-loop response, so even
though the system has three or four poles, it may still act like a second or even first order system
depending on the location(s) of the dominant pole(s).

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

62
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

How do we design a feed-back controller for the system by using the root locus method? Say our
design criteria are 5% overshoot and 1 second rise time. Make a MATLAB file called rl.m. Enter
the transfer function, and the command to plot the root locus:
num=[1 7];
den=conv(conv([1 0],[1 5]),conv([1 15],[1 20]));
sys=tf(num,den);
rlocus(sys)
axis([-22 3 -15 15])

## Choosing a value of K from the root locus

The plot above shows all possible closed-loop pole locations for a pure proportional controller.
Obviously not all of those closed-loop poles will satisfy our design criteria. To determine what
part of the locus is acceptable, we can use the command sgrid(Zeta,Wn) to plot lines of constant
damping ratio and natural frequency. Its two arguments are the damping ratio (Zeta) and natural
frequency (Wn) [these may be vectors if you want to look at a range of acceptable values]. In our
problem, we need an overshoot less than 5% (which means a damping ratio Zeta of greater than
0.7) and a rise time of 1 second (which means a natural frequency Wn greater than 1.8). Enter in
the MATLAB command window:

zeta=0.7;
Wn=1.8;
sgrid(zeta, Wn)

On the plot above, the two dotted lines at about a 45 degree angle indicate pole locations with
Zeta = 0.7; in between these lines, the poles will have Zeta > 0.7 and outside of the lines Zeta <
0.7. The semicircle indicates pole locations with a natural frequency Wn = 1.8; inside the circle,
Wn < 1.8 and outside the circle Wn > 1.8.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

63
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Going back to our problem, to make the overshoot less than 5%, the poles have to be in between
the two white dotted lines, and to make the rise time shorter than 1 second, the poles have to be
outside of the white dotted semicircle. So now we know only the part of the locus outside of the
semicircle and in between the two lines are acceptable. All the poles in this location are in the left-
half plane, so the closed-loop system will be stable.

From the plot above we see that there is part of the root locus inside the desired region. So in this
case we need only a proportional controller to move the poles to the desired region. You can use
rlocfind command in MATLAB to choose the desired poles on the locus:

[k,poles] = rlocfind(sys)
Click on the plot the point where you want the closed-loop pole to be. You may want to select the
points indicated in the plot below to satisfy the design criteria.

Note that since the root locus may has more than one branch, when you select a pole, you may
want to find out where the other pole (poles) are. Remember they will affect the response too.
From the plot above we see that all the poles selected (all the "+" signs) are at reasonable
positions. We can go ahead and use the chosen k as our proportional controller.

Closed-loop response : In order to find the step response, you need to know the closed-
loop transfer function. You could compute this using the rules of block diagrams, or let MATLAB
do it for you

sys_cl= feedback(k*sys,1)

The two arguments to the function feedback are the numerator and denominator of the
open-loop system. You need to include the proportional gain that you have chosen. Unity
feedback is assumed.

If you have a non-unity feedback situation, look at the help file for the MATLAB function
feedback, which can find the closed-loop transfer function with a gain in the feedback loop.
Check out the step response of your closed-loop system:
step(sys_cl)

As we expected, this response has an overshoot less than 5% and a rise time less than 1 second.
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
64
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

PID Controller

Introduction
This tutorial will show you the characteristics of the each of proportional (P), the integral (I), and
the derivative (D) controls, and how to use them to obtain a desired response. In this tutorial, we
will consider the following unity feedback system:

## Plant: A system to be controlled

Controller: Provides the excitation for the plant; Designed to control the overall system
behavior

## The three-term controller

The transfer function of the PID controller looks like the following:

• Kp = Proportional gain
• KI = Integral gain
• Kd = Derivative gain

First, let's take a look at how the PID controller works in a closed-loop system using the
schematic shown above. The variable (e) represents the tracking error, the difference between the
desired input value (R) and the actual output (Y). This error signal (e) will be sent to the PID
controller, and the controller computes both the derivative and the integral of this error signal. The
signal (u) just past the controller is now equal to the proportional gain (Kp) times the magnitude
of the error plus the integral gain (Ki) times the integral of the error plus the derivative gain (Kd)
times the derivative of the error.

This signal (u) will be sent to the plant, and the new output (Y) will be obtained. This new output
(Y) will be sent back to the sensor again to find the new error signal (e). The controller takes this
new error signal and computes its derivative and its integral again. This process goes on and on.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

65
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## The characteristics of P, I, and D controllers

A proportional controller (Kp) will have the effect of reducing the rise time and will reduce but
never eliminate the steady-state error. An integral control (Ki) will have the effect of eliminating
the steady-state error, but it may make the transient response worse. A derivative control (Kd) will
have the effect of increasing the stability of the system, reducing the overshoot, and improving the
transient response. Effects of each of controllers Kp, Kd, and Ki on a closed-loop system are
summarized in the table shown below.

## CL RESPONSE RISE TIME OVERSHOOT SETTLING TIME S-S ERROR

Kp Decrease Increase Small Change Decrease
Ki Decrease Increase Increase Eliminate
Kd Small Change Decrease Decrease Small Change

Note that these correlations may not be exactly accurate, because Kp, Ki, and Kd are dependent
on each other. In fact, changing one of these variab can change the effect of the other two. For this
reason, the table should only be used as a reference when you are determining the values for Ki,
Kp and Kd.

Example Problem

(1)

## Taking the Laplace transform of the modeling equation (1), we get

The transfer function between the displacement X(s) and the input F(s) then becomes

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

66
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Let

• M = 1kg
• b = 10 N.s/m
• k = 20 N/m
• F(s) = 1

## Plug these values into the above transfer function

The goal of this problem is to show you how each of Kp, Ki and Kd contributes to obtain

## • Fast rise time

• Minimum overshoot
• No steady-state error

## Open-loop step response

Let's first view the open-loop step response. Create a new m-file and add in the following code:

num=1;
den=[1 10 20];
plant=tf(num,den);
step(plant)

Running this m-file in the MATLAB command window should give you the plot shown below.

The DC gain of the plant transfer function is 1/20, so 0.05 is the final value of the output to an
unit step input. This corresponds to the steady-state error of 0.95, quite large indeed. Furthermore,
the rise time is about one second, and the settling time is about 1.5 seconds. Let's design a
controller that will reduce the rise time, reduce the settling time, and eliminates the steady-state
error.

Proportional control
From the table shown above, we see that the proportional controller (Kp) reduces the rise time,
increases the overshoot, and reduces the steady-state error. The closed-loop transfer function of
the above system with a proportional controller is:
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
67
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Let the proportional gain (Kp) equal 300 and change the m-file to the following:

Kp=300;
contr=Kp;
sys_cl=feedback(contr*plant,1);
t=0:0.01:2;
step(sys_cl,t)

Running this m-file in the MATLAB command window should give you the following plot.

Note: The MATLAB function called feedback was used to obtain a closed-loop transfer function
directly from the open-loop transfer function (instead of computing closed-loop transfer function
by hand).

The above plot shows that the proportional controller reduced both the rise time and the steady-
state error, increased the overshoot, and decreased the settling time by small amount.

Proportional-Derivative control

Now, let's take a look at a PD control. From the table shown above, we see that the derivative
controller (Kd) reduces both the overshoot and the settling time. The closed-loop transfer function
of the given system with a PD controller is:

Let Kp equal 300 as before and let Kd equal 10. Enter the following commands into an m-file and
run it in the MATLAB command window.

Kp=300;
Kd=10;
contr=tf([Kd Kp],1);
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
68
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

sys_cl=feedback(contr*plant,1);
t=0:0.01:2;
step(sys_cl,t)

This plot shows that the derivative controller reduced both the overshoot and the settling time, and
had a small effect on the rise time and the steady-state error.

Proportional-Integral control

Before going into a PID control, let's take a look at a PI control. From the table, we see that an
integral controller (Ki) decreases the rise time, increases both the overshoot and the settling time,
and eliminates the steady-state error. For the given system, the closed-loop transfer function with
a PI control is:

Let's reduce the Kp to 30, and let Ki equal 70. Create an new m-file and enter the following
commands.

Kp=30;
Ki=70;
contr=tf([Kp Ki],[1 0]);
sys_cl=feedback(contr*plant,1);
t=0:0.01:2;
step(sys_cl,t)
Run this m-file in the MATLAB command window, and you should get the following plot.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

69
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

We have reduced the proportional gain (Kp) because the integral controller also reduces the rise
time and increases the overshoot as the proportional controller does (double effect). The above
response shows that the integral controller eliminated the steady-state error.

Proportional-Integral-Derivative control

Now, let's take a look at a PID controller. The closed-loop transfer function of the given system
with a PID controller is:

After several trial and error runs, the gains Kp=350, Ki=300, and Kd=50 provided the desired
response. To confirm, enter the following commands to an m-file and run it in the command
window. You should get the following step response.

Kp=350;
Ki=300;
Kd=50;
contr=tf([Kd Kp Ki],[1 0]);
sys_cl=feedback(contr*plant,1);
t=0:0.01:2;
step(sys_cl,t)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

70
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Now, we have obtained a closed-loop system with no overshoot, fast rise time, and no steady-state
error.

## General tips for designing a PID controller

When you are designing a PID controller for a given system, follow the steps shown below to
obtain a desired response.

## 1. Obtain an open-loop response and determine what needs to be improved

2. Add a proportional control to improve the rise time
3. Add a derivative control to improve the overshoot
4. Add an integral control to eliminate the steady-state error
5. Adjust each of Kp, Ki, and Kd until you obtain a desired overall response. You can always
refer to the table shown in this "PID Tutorial" page to find out which controller controls
what characteristics.

Lastly, please keep in mind that you do not need to implement all three controllers (proportional,
derivative, and integral) into a single system, if not necessary. For example, if a PI controller
gives a good enough response (like the above example), then you don't need to implement a
derivative controller on the system. Keep the controller as simple as possible.

Code:
% This Matlab code simulates a PID controller for a fisrt order time delay
system
% G(s) = (K*e(-theta*s))/(T*s+1)

## T=360; K=14.9; theta= 80; % System Parameters

refe = 10; % Reference to follow
Tf = 1000; % Simulation time
yold = 0;yold1=0;
yp = []; ys_prime = [];
er = refe; % Error (Initial error = Reference)
er1 = 0; % First derivative of error
er2 = 0; % Second derivative of error
eold = refe; eold2 = 0;
dt = 1;
for i=1:dt:Tf
dtspan = [i i+dt];
eold2 = eold ;
eold = er;
er = refe - yold;
er2 = er + eold2 - 2*eold;
er1 = er - eold;
init_con = [yold ; (yold-yold1)]; % Initial conditions for the
diffirential equations
options = [];
[t,y] = ode45(@pid_ctrl,dtspan,init_con,options,er,er1,er2);
yold1 = yold;
ys = y(length(y),1);
if i <= theta
ys_prime = [0 ys_prime];
else
ys_prime = [ys ys_prime];
end
yold = ys_prime(1);
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
71
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

yp = [yp yold];
end

plot(yp);
xlabel('Time');
ylabel('Output');
title('Output of the system with PID Controller');
grid on;

pid_ctrl.m
function yprime = pid_ctrl(t,y,er,er1,er2)

## T=360; K=14.9; % System parametrs

Kp = 0.5; Ki = 0.05; Kd = 3; % PID Controller parametrs

## yprime = [y(2); ((1/T)*(-y(2)+ K*Kd*er2 + K*Kp*er1 + K*Ki*er))];

Bode Plots
As noted above, a Bode plot is the representation of the magnitude and phase of G(j*w) (where
the frequency vector w contains only positive frequencies). To see the Bode plot of a transfer
function, you can use the MATLAB bode command. For example,
num = 50;
den = [1 9 30 40];
sys = tf(num,den);
bode(sys)
displays the Bode plots for the transfer function:
50
-----------------------
s^3 + 9 s^2 + 30 s + 40

Please note the axes of the figure. The frequency is on a logarithmic scale, the phase is given in
degrees, and the magnitude is given as the gain in decibels.

## Note: a decibel is defined as 20*log10 ( |G(j*w| )

Gain and Phase Margin
Let's say that we have the following system:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

72
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

where K is a variable (constant) gain and G(s) is the plant under consideration. The gain margin
is defined as the change in open loop gain required to make the system unstable. Systems with
greater gain margins can withstand greater changes in system parameters before becoming
unstable in closed loop.

Keep in mind that unity gain in magnitude is equal to a gain of zero in dB.

The phase margin is defined as the change in open loop phase shift required to make a closed
loop system unstable.

The phase margin also measures the system's tolerance to time delay. If there is a time delay
greater than 180/Wpc in the loop (where Wpc is the frequency where the phase shift is 180 deg),
the system will become unstable in closed loop. The time delay can be thought of as an extra
block in the forward path of the block diagram that adds phase to the system but has no effect the
gain. That is, a time delay can be represented as a block with magnitude of 1 and phase

For now, we won't worry about where all this comes from and will concentrate on identifying the
gain and phase margins on a Bode plot.

The phase margin is the difference in phase between the phase curve and -180 deg at the point
corresponding to the frequency that gives us a gain of 0dB (the gain cross over frequency, Wgc).
Likewise, the gain margin is the difference between the magnitude curve and 0dB at the point
corresponding to the frequency that gives us a phase of -180 deg (the phase cross over frequency,
Wpc).

One nice thing about the phase margin is that you don't need to replot the Bode in order to find the
new phase margin when changing the gains. If you recall, adding gain only shifts the magnitude
plot up. This is the equivalent of changing the y-axis on the magnitude plot. Finding the phase
margin is simply the matter of finding the new cross-over frequency and reading off the phase
margin. For example, suppose you entered the command bode(sys). You will get the following
bode plot:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

73
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

You should see that the phase margin is about 100 degrees. Now suppose you added a gain of
100, by entering the command bode(100*sys). You should get the following plot (note we
changed the axis so the scale would be the same as the plot above, your bode plot may not be
exactly the same shape, depending on the scale used):

As you can see the phase plot is exactly the same as before, and the magnitude plot is shifted up
by 40dB (gain of 100). The phase margin is now about -60 degrees. This same result could be
achieved if the y-axis of the magnitude plot was shifted down 40dB. Try this, look at the first
Bode plot, find where the curve crosses the -40dB line, and read off the phase margin. It should be
about -60 degrees, the same as the second Bode plot.

We can find the gain and phase margins for a system directly, by using MATLAB. Just use the
margin command. This command returns the gain and phase margins, the gain and phase cross
over frequencies, and a graphical representation of these on the Bode plot. Let's check it out:

margin(sys)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

74
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Bandwidth Frequency
The bandwidth frequency is defined as the frequency at which the closed-loop magnitude
response is equal to -3 dB. However, when we design via frequency response, we are interested in
predicting the closed-loop behavior from the open-loop response. Therefore, we will use a
second-order system approximation and say that the bandwidth frequency equals the frequency at
which the open-loop magnitude response is between -6 and - 7.5dB, assuming the open loop
phase response is between -135 deg and -225 deg. For a complete derivation of this
approximation, consult your textbook.

In order to illustrate the importance of the bandwidth frequency, we will show how the output
changes with different input frequencies. We will find that sinusoidal inputs with frequency less
than Wbw (the bandwidth frequency) are tracked "reasonably well" by the system. Sinusoidal
inputs with frequency greater than Wbw are attenuated (in magnitude) by a factor of 0.707 or
greater (and are also shifted in phase).

Let's say that we have the following closed-loop transfer function representing a system:

1
---------------
s^2 + 0.5 s + 1
First of all, let's find the bandwidth frequency by looking at the Bode plot:
num = 1;
den = [1 0.5 1];
sys = tf(num,den);
bode (sys)

Since this is the closed-loop transfer function, our bandwidth frequency will be the frequency
corresponding to a gain of -3 dB. looking at the plot, we find that it is approximately 1.4 rad/s. We
can also read off the plot that for an input frequency of 0.3 radians, the output sinusoid should
have a magnitude about one and the phase should be shifted by perhaps a few degrees (behind the
input). For an input frequency of 3 rad/sec, the output magnitude should be about -20dB (or 1/10
as large as the input) and the phase should be nearly -180 (almost exactly out-of-phase). We can
use the lsim command to simulate the response of the system to sinusoidal inputs.

First, consider a sinusoidal input with a frequency lower than Wbw. We must also keep in mind
that we want to view the steady state response. Therefore, we will modify the axes in order to see
the steady state response clearly (ignoring the transient response).

w = 0.3;
num = 1;
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
75
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## den = [1 0.5 1];

sys = tf(num,den);
t = 0:0.1:100;
u = sin(w*t);
[y,t] = lsim(sys,u,t);
plot(t,y,t,u)
axis([50,100,-2,2])

Note that the output (blue) tracks the input (purple) fairly well; it is perhaps a few degrees behind
the input as expected.

However, if we set the frequency of the input higher than the bandwidth frequency for the
system, we get a very distorted response (with respect to the input):

w = 3;
num = 1;
den = [1 0.5 1];
sys = tf(num,den);
t = 0:0.1:100;
u = sin(w*t);
[y,t] = lsim(sys,u,t);
plot(t,y,t,u)
axis([90, 100, -1, 1])

Again, note that the magnitude is about 1/10 that of the input, as predicted, and that it is almost
exactly out of phase (180 degrees behind) the input. Feel free to experiment and view the response
for several different frequencies w, and see if they match the Bode plot.

Closed-loop performance
In order to predict closed-loop performance from open-loop frequency response, we need to have
several concepts clear:

• The system must be stable in open loop if we are going to design via Bode plots.
• If the gain cross over frequency is less than the phase cross over frequency (i.e. Wgc <
Wpc), then the closed-loop system will be stable.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

76
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

• For second-order systems, the closed-loop damping ratio is approximately equal to the
phase margin divided by 100 if the phase margin is between 0 and 60 deg. We can use this
concept with caution if the phase margin is greater than 60 deg.
• A very rough estimate that you can use is that the bandwidth is approximately equal to the
natural frequency.

Let's use these concepts to design a controller for the following system:

10
----------
1.25s + 1

## • Zero steady state error.

• Maximum overshoot must be less than 40%.
• Settling time must be less than 2 secs.

There are two ways of solving this problem: one is graphical and the other is numerical. Within
MATLAB, the graphical approach is best, so that is the approach we will use. First, let's look at the
Bode plot. Create an m-file with the following code:
num = 10;
den = [1.25,1];
sys = tf(num,den);
bode(sys)

There are several several characteristics of the system that can be read directly from this Bode
plot. First of all, we can see that the bandwidth frequency is around 10 rad/sec. Since the
bandwidth frequency is roughly the same as the natural frequency (for a first order system of this
type), the rise time is 1.8/BW=1.8/10=1.8 seconds. This is a rough estimate, so we will say the
rise time is about 2 seconds.

The phase margin for this system is approximately 95 degrees. The relation damping ratio =
pm/100 only holds for PM < 60/ Since the system is first-order, there should be no overshoot.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

77
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The last major point of interest is steady-state error. The steady-state error can be read directly off
the Bode plot as well. The constant (Kp, Kv, or Ka) is found from the intersection of the low
frequency asymptote with the w=1 line. Just extend the low frequency line to the w=1 line. The
magnitude at this point is the constant. Since the Bode plot of this system is a horizontal line at
low frequencies (slope = 0), we know this system is of type zero. Therefore, the intersection is
easy to find. The gain is 20dB (magnitude 10). What this means is that the constant for the error
function it 10. The steady-state error is 1/(1+Kp)=1/(1+10)=0.091. If our system was type one
instead of type zero, the constant for the steady-state error would be found in a manner similar to
the following

Let's check our predictions by looking at a step response plot. This can be done by adding the
following two lines of code into the MATLAB command window.

sys_cl = feedback(sys,1);
step(sys_cl)

As you can see, our predictions were very good. The system has a rise time of about 2 seconds,
has no overshoot, and has a steady-state error of about 9%. Now we need to choose a controller
that will allow us to meet the design criteria. We choose a PI controller because it will yield zero
steady state error for a step input. Also, the PI controller has a zero, which we can place. This
gives us additional design flexibility to help us meet our criteria. Recall that a PI controller is
given by:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

78
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

K*(s+a)
Gc(s) = -------
s
The first thing we need to find is the damping ratio corresponding to a percent overshoot of 40%.
Plugging in this value into the equation relating overshoot and damping ratio (or consulting a plot
of this relation), we find that the damping ratio corresponding to this overshoot is approximately
0.28. Therefore, our phase margin should be at least 30 degrees. We must have a bandwidth
frequency greater than or equal to 12 if we want our settling time to be less than 1.75 seconds
which meets the design specs.

Now that we know our desired phase margin and bandwidth frequency, we can start our design.
Remember that we are looking at the open-loop Bode plots. Therefore, our bandwidth frequency
will be the frequency corresponding to a gain of approximately -7 dB.

Let's see how the integrator portion of the PI or affects our response. Change your m-file to look
like the following (this adds an integral term but no proportional term):

num = 10;
den = [1.25 1];
plant = tf(num,den);
numPI = 1;
denPI = [1 0];
contr = tf(numPI,denPI);
bode(contr * plant, logspace(0,2))

Our phase margin and bandwidth frequency are too small. We will add gain and phase with a
zero. Let's place the zero at 1 for now and see what happens. Change your m-file to look like the
following:

num = 10;
den = [1.25 1];
plant = tf(num,den);
numPI = [1 1];
denPI = [1 0];
contr = tf(numPI,denPI);
bode(contr * plant, logspace(0,2))

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

79
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

It turns out that the zero at 1 with a unit gain gives us a satisfactory answer. Our phase margin is
greater than 60 degrees (even less overshoot than expected) and our bandwidth frequency is
approximately 11 rad/s, which will give us a satisfactory response. Although satisfactory, the
response is not quite as good as we would like. Therefore, let's try to get a higher bandwidth
frequency without changing the phase margin too much. Let's try to increase the gain to 5 and see
what happens. This will make the gain shift and the phase will remain the same.

num = 10;
den = [1.25 1];
plant = tf(num,den);
numPI = 5*[1 1];
denPI = [1 0];
contr = tf(numPI,denPI);
bode(contr * plant, logspace(0,2))

That looks really good. Let's look at our step response and verify our results. Add the following
two lines to your m-file:

step(sys_cl)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

80
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

## Sample Bode Plots

Let's say that we have the following system:

We can view the open loop Bode plot of this system by looking at the Bode plot of Gc(s)G(s).
However, we can also view the Bode plots of G(s) and of Gc(s) and add them graphically.
Therefore, if we know the frequency response of simple functions, we can use them to our
advantage when we are designing a controller:

bode(1, [1 0])

1
---
s

bode(1, [1 1])
1
------
s + 1

bode([1 0], 1)
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
81
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

bode([1 1], 1)

s+1

Note that the location of the pole or zero(a) will greatly affect the frequency response. If we have
a pole close to the origin, the response at lower frequencies will undergo the most drastic changes.
If we have a pole or zero farther from the origin, the response at higher frequencies will undergo
the most drastic changes. Also remember that a change in gain will shift the entire gain response
up or down and will not affect the phase. Let's see a couple of examples:

bode(1,[ 1, 0.1])

1
------
s + 0.1

bode(1,[ 1, 10])

1
------
s + 10

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

82
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

bode([1, 0.1],1)

s + 0.1

bode([1, 10],1)

s + 10

Modifying the location of these poles or zeros, we can manipulate the frequency response of the
combined system to something that will suit our purposes.

## The Nyquist Diagram

The Nyquist plot allows us to predict the stability and performance of a closed-loop system by
observing its open-loop behavior. The Nyquist criterion can be used for design purposes
regardless of open-loop stability (remember that the Bode design methods assume that the system
is stable in open loop). Therefore, we use this criterion to determine closed-loop stability when the
Bode plots display confusing information.
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
83
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The Nyquist diagram is basically a plot of G(j* w) where G(s) is the open-loop transfer function
and w is a vector of frequencies which encloses the entire right-half plane. In drawing the Nyquist
diagram, both positive and negative frequencies (from zero to infinity) are taken into account. We
will represent positive frequencies in red and negative frequencies in green. The frequency vector
used in plotting the Nyquist diagram usually looks like this (if you can imagine the plot stretching
out to infinity):

However, if we have open-loop poles or zeros on the jw axis, G(s) will not be defined at those
points, and we must loop around them when we are plotting the contour. Such a contour would
look as follows:

Please note that the contour loops around the pole on the jw axis. As we mentioned before, the
MATLAB nyquist command does not take poles or zeros on the jw axis into account and
therefore produces an incorrect plot. To correct this, please download and use nyquist1.m. If we
have a pole on the jw axis, we have to use nyquist1. If there are no poles or zeros on the jw-axis,
or if we have pole-zero cancellation, we can use either the nyquist command or nyquist1.m.

## The Cauchy criterion

The Cauchy criterion (from complex analysis) states that when taking a closed contour in the
complex plane, and mapping it through a complex function G(s), the number of times that the plot
of G(s) encircles the origin is equal to the number of zeros of G(s) enclosed by the frequency
contour minus the number of poles of G(s) enclosed by the frequency contour. Encirclements of
the origin are counted as positive if they are in the same direction as the original closed contour or
negative if they are in the opposite direction.

When studying feedback controls, we are not as interested in G(s) as in the closed-loop transfer
function:

G(s)
---------
1 + G(s)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

84
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

If 1+ G(s) encircles the origin, then G(s) will enclose the point -1. Since we are interested in the
closed-loop stability, we want to know if there are any closed-loop poles (zeros of 1 + G(s)) in the
right-half plane. More details on how to determine this will come later.

Therefore, the behavior of the Nyquist diagram around the -1 point in the real axis is very
important; however, the axis on the standard nyquist diagram might make it hard to see what's
happening around this point. To correct this, you can add the lnyquist.m function to your files.
The lnyquist.m command plots the Nyquist diagram using a logarithmic scale and preserves the
characteristics of the -1 point.

To view a simple Nyquist plot using MATLAB, we will define the following transfer function and
view the Nyquist plot:

0.5
-------
s - 0.5
sys=tf(0.5,[1 -0.5]);
nyquist(sys)

Now we will look at the Nyquist diagram for the following transfer function:
s + 2
-----
s^2
Note that this function has a pole at the origin. We will see the difference between using the
nyquist, nyquist1, and lnyquist commands with this particular function.
num = [1 2];
den = [1 0 0];
sys = tf(num,den);

nyquist(sys)

nyquist1(sys)

lnyquist(sys)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

85
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Note that the nyquist plot is not the correct one, the nyquist1 plot is correct, but it's hard to see
what happens close to the -1 point, and the lnyquist plot is correct and has an appropriate scale.

## Closed Loop Stability

Consider the negative feedback system:

Remember from the Cauchy criterion that the number N of times that the plot of G(s)H(s)
encircles -1 is equal to the number Z of zeros of 1 + G(s)H(s) enclosed by the frequency contour
minus the number P of poles of 1 + G(s)H(s) enclosed by the frequency contour (N = Z - P).
Keeping careful track of open- and closed-loop transfer functions, as well as numerators and
denominators, you should convince yourself that:

• the zeros of 1 + G(s)H(s) are the poles of the closed-loop transfer function
• the poles of 1 + G(s)H(s) are the poles of the open-loop transfer function.

## • P = the number of open-loop (unstable) poles of G(s)H(s)

• N = the number of times the Nyquist diagram encircles -1
• clockwise encirclements of -1 count as positive encirclements
• counter-clockwise (or anti-clockwise) encirclements of -1 count as negative encirclements
• Z = the number of right half-plane (positive, real) poles of the closed-loop system

## The important equation which relates these three quantities is:

Z = P + N
Note: This is only one convention for the Nyquist criterion. Another convention states that a
positive N counts the counter-clockwise or anti-clockwise encirclements of -1. The P and Z
variab remain the same. In this case the equation becomes Z = P - N. Throughout these
tutorials, we will use a positive sign for clockwise encirclements.
It is very important (and somewhat tricky) to learn how to count the number of times that the
diagram encircles -1.

Another way of looking at it is to imagine you are standing on top of the -1 point and are
following the diagram from beginning to end. Now ask yourself: How many times did I turn my
head a full 360 degrees? Again, if the motion was clockwise, N is positive, and if the motion is
anti-clockwise, N is negative.

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

86
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

Knowing the number of right-half plane (unstable) poles in open loop (P), and the number of
encirclements of -1 made by the Nyquist diagram (N), we can determine the closed-loop stability
of the system. If Z = P + N is a positive, nonzero number, the closed-loop system is unstable.

We can also use the Nyquist diagram to find the range of gains for a closed-loop unity feedback
system to be stable. The system we will test looks like this:

where G(s) is :
s^2 + 10 s + 24
---------------
s^2 - 8 s + 15
This system has a gain K which can be varied in order to modify the response of the closed-loop
system. However, we will see that we can only vary this gain within certain limits, since we have
to make sure that our closed-loop system will be stable. This is what we will be looking for: the
range of gains that will make this system stable in the closed loop.

The first thing we need to do is find the number of positive real poles in our open-loop transfer
function:

roots([1 -8 15])

ans =
5
3
The poles of the open-loop transfer function are both positive. Therefore, we need two anti-
clockwise (N = -2) encirclements of the Nyquist diagram in order to have a stable closed-loop
system (Z = P + N). If the number of encirclements is less than two or the encirclements are not
anti-clockwise, our system will be unstable.

## sys = tf([ 1 10 24], [ 1 -8 15]);

nyquist(sys)

There are two anti-clockwise encirclements of -1. Therefore, the system is stable for a gain of 1.
Now we will see how the system behaves if we increase the gain to 20:

nyquist(20*sys)

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

87
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The diagram expanded. Therefore, we know that the system will be stable no matter how much
we increase the gain. However, if we decrease the gain, the diagram will contract and the system
might become unstable. Let's see what happens for a gain of 0.5:

nyquist(0.5*sys)

The system is now unstable. By trial and error we find that this system will become unstable for
gains less than 0.80. We can verify our answers by zooming in on the Nyquist plots as well as by
looking at the closed-loop steps responses for gains of 0.79, 0.80, and 0.81.

Gain Margin
We already defined the gain margin as the change in open-loop gain expressed in decibels (dB),
required at 180 degrees of phase shift to make the system unstable. Now we are going to find out
where this comes from. First of all, let's say that we have a system that is stable if there are no
Nyquist encirclements of -1, such as :
50
-----------------------
s^3 + 9 s^2 + 30 s + 40
Looking at the roots, we find that we have no open loop poles in the right half plane and therefore
no closed-loop poles in the right half plane if there are no Nyquist encirclements of -1. Now, how
much can we vary the gain before this system becomes unstable in closed loop? Let's look at the
following figure:

## NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.

88
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

The open-loop system represented by this plot will become unstable in closed loop if the gain is
increased past a certain boundary. The negative real axis area between -1/a (defined as the point
where the 180 degree phase shift occurs...that is, where the diagram crosses the real axis) and -1
represents the amount of increase in gain that can be tolerated before closed-loop instability.

If we think about it, we realize that if the gain is equal to a, the diagram will touch the -1 point:

Therefore, we say that the gain margin is 'a' units. However, we mentioned before that the gain
margin is usually measured in decibels. Hence, the gain margin is :
GM = 20*log10(a) [dB]
We will now find the gain margin of the stable, open-loop transfer function we viewed before.
Recall that the function is:
50
-----------------------
s^3 + 9 s^2 + 30 s + 40
and that the Nyquist diagram can be viewed by typing:
sys = tf(50, [1 9 30 40 ]);
nyquist(sys)

As we discussed before, all that we need to do to find the gain margin is find 'a', as defined in the
preceding figure. To do this, we need to find the point where there is exactly 180 degrees of phase
shift. This means that the transfer function at this point is real (has no imaginary part). The
numerator is already real, so we just need to look at the denominator. When s = j*w, the only
terms in the denominator that will have imaginary parts are those which are odd powers of s.
Therefore, for G(j*w) to be real, we must have:

-j w^3 + 30 j w = 0
which means w=0 (this is the rightmost point in the Nyquist diagram) or w=sqrt(30). We can then
find the value of G(j*w) at this point using polyval:
w=sqrt(30);
polyval(50,j*w)/polyval([1 9 30 40],j*w)
You should get the following output from MATLAB
ans = -0.2174
The answer is: -0.2174 + 0i. The imaginary part is zero, so we know that our answer is correct.
We can also verify by looking at the Nyquist plot again. The real part also makes sense. Now we
can proceed to find the gain margin.

We found that the 180 degrees phase shift occurs at -0.2174 + 0i. This point was previously
defined as -1/a. Therefore, we now have 'a', which is the gain margin. However, we need to
express the gain margin in decibels,

-1/a = -0.2174
NITTE M EENAKSHI INSTITUTE OF TECHNOLOGY, BANGALORE.
89
MAT LAB MANUAL DEPT OF ELECTRONICS AND COMMUNICATION ENGG

=> a = 4.6
=> GM = 20*log10( 4.6) = 13.26 dB
We now have our gain margin. Let's see how accurate it is by using a gain of a = 4.6 and zooming
in on the Nyquist plot:
a = 4.6
nyquist(a*sys)

The plot appears to go right through the -1 point. We will now verify the accuracy of our results
by viewing the zoomed Nyquist diagrams and step responses for gains of 4.5, 4.6, and 4.7.

Phase Margin
We have already discussed the importance of the phase margin. Therefore, we will only talk about
where this concept comes from. We have defined the phase margin as the change in open-loop
phase shift required at unity gain to make a closed-loop system unstable. Let's look at the
following graphical definition of this concept to get a better idea of what we are talking about.

Let's analyze the previous plot and think about what is happening. From our previous example we
know that this particular system will be unstable in closed loop if the Nyquist diagram encircles
the -1 point. However, we must also realize that if the diagram is shifted by theta degrees, it will
then touch the -1 point at the negative real axis, making the system marginally stable in closed
loop. Therefore, the angle required to make this system marginally stable in closed loop is called
the phase margin (measured in degrees). In order to find the point we measure this angle from, we
draw a circle with radius of 1, find the point in the Nyquist diagram with a magnitude of 1 (gain
of zero dB), and measure the phase shift needed for this point to be at an angle of 180 deg.

90