Upload
srivas0007
View
217
Download
0
Embed Size (px)
Citation preview
8/8/2019 Simulation Lab 4-06-2010
1/88
Simulation Lab
CONTENTS
S.No Experiments Page. No
1 Basic Operations on Matrices. 3
2 Generation of Various signals and sequences (Periodic
and Aperiodic) such as Unit Impulse, Unit Step,
Square, Saw tooth, Triangular, Sinusoidal, Ramp, Sinc.
6
3 Operations on Signals and Sequences such as Addition,
Multiplication, Scaling, Shifting, Folding,
Computation of Energy and Average Power.
16
4 Finding the Even and Odd parts of Signal/Sequence
and Real and Imaginary Parts of Signal.
23
5 Convolution between Signals and Sequences. 25
6 Auto Correlation and Cross Correlation between
Signals and Sequences
29
7 Computation of unit sample, unit step and sinusoidal
response of the given LTI system and verifying its
physical realiazability and stability properties.
32
8 Gibbs Phenomenon. 38
9 Sampling Theorem Verification. 40
10 Locating the Zeros and Poles and Plotting the Pole-
Zero maps in the S-Plane and Z-Plane for the given
transfer function.
43
1
8/8/2019 Simulation Lab 4-06-2010
2/88
S.No Experiments Page. No
11 Wave form Synthesis using Laplace Transform
12 Verification of Linearity and Time Invariance
Properties of a given Continuous / Discrete System13 Generation of Gaussian noise (Real and Complex),
Computation of its Mean, Mean Square Value and its
Skew, Kurtosis, and PSD , Probability Distribution
Function.
14 Finding the Fourier Transform of a given Signal and
plotting its magnitude and phase spectrum.
15 Removal of Noise by Autocorrelation / Cross
Correlation.
16 Extraction of Periodic Signal Masked by Noise using
Correlation.
17 Verification of Weiner Khinchine Relations.
18 Checking a Random Process for Stationary in Wide
sense.
2
8/8/2019 Simulation Lab 4-06-2010
3/88
MATLAB is an environment for performing calculations and simulations of
a variety of types. MATLAB, short for matrix laboratory, was developed
by Cleve Moler, a professor of mathematics and computer science, in the
late 70s and early 80s. In 1984, Cleve Moler and Jack Little founded The
Math Works which has been developing MATLAB ever since. In the earliest
version of MATLAB, there were about 80 commands, and they allowed for
matrix calculations. Now there are thousands of commands, and there are
many, many types of calculations that one can perform. .Simulink is a
MATLAB add-on that allows one to simulate systems by combining
blocks of various types. the student will learn how to make calculations
using MATLAB and will learn a little about simulating systems using the
simulation tools provided by MATLAB and Simulink .
Some Very Basic Instructions to start MATLAB:
Double click on the MATLAB icon on the computers desktop. This opens
the main MATLAB window. When working with MATLAB there are two
ways of programming. One can either enter commands in the command
window, or one can write functions using the M-file editor. The basic
MATLAB interface is pretty easy to use.
MATLAB does not require that variables be declared. MATLAB allocates
space for the variable the first time the variable is used. To assign a value to
a variable, one uses an equal sign. To set x equal to 2, one writes x = 2.
When one does this, MATLAB replies with: x = 2
MATLAB as a Vector-enabled Calculator:
Two features make MATLAB particularly useful. MATLAB knows how to
work with vectors, and it knows how to produce all sorts of graphs. To
define a vector, an ordered set of numbers that will be represented by the
letter aone types a = [num1 num2 num3 ... numN]. (One can insert
3
8/8/2019 Simulation Lab 4-06-2010
4/88
commas between the different elements, but MATLAB does not require that
one insert them.) MATLAB recognizes this as a command to allocate
memory fora and to assign the set of numbers listed to a.
For example, giving MATLAB the command a = [1 2 3 4 5] causes
MATLAB to respond with a = 1 2 3 4 5
Once a has been defined there are many ways that it can be processed. Most
MATLAB functions are vectorized; they can take vector arguments, and
they will return vectors as answers. When using MATLAB, to calculate the
sine of , one types sin(pi). To calculate the value of sine at the points , 5
one could give MATLAB five separate commands; that is not necessary,
however. Instead, one can type sin (pi*a). (The asterisk
Denotes multiplication. MATLAB does not understand that if one writes
ab one would like MATLAB to multiply to elements. One must always tell
MATLAB to multiply them.) MATLAB will respond to the command with
ans = 1.0e-015 * 0.1225 -0.2449 0.3674 -0.4899 0.6123
In mathematics, one can add vectors and the same is true when using
MATLAB. The following set of commands is legal, and the answer given is
what MATLAB would reply with.
>> a = [1 2 3]
a =
1 2 3
>> b = [4 5 6]
b =
4 5 6
>> a+b
ans = 5 7 9
4
8/8/2019 Simulation Lab 4-06-2010
5/88
MATLAB has many functions that allow one to plot data. We consider some
of the simplest uses of the simplest of the plotting functions: plot. If one
types plot(a), MATLAB plots the values of a against the integers. For
example, giving MATLAB the command plot(1:2:10 ) .By default, plot
interpolates between the points in a plot.) If one gives MATLAB the
command plot(t,a), then MATLAB plots the vector a against the vector t.
Suppose that one gives MATLAB the commands Using the Editor One can
open the MATLAB editor either by typing edit at the MATLAB command
prompt or by clicking on the blank page on the toolbar on the MATLAB
window. (If one would like to open a file in the editor, then one clicks on the
folder on the toolbar, selects the relevant file, and then clicks on it.
MATLAB will open the file in the editor.)
The editor is a damped exponential. sensitive and has many nice features.
When one is finished writing a file, one saves it. MATLAB expects files that
contain MATLAB commands to end with a .m. After saving a file, one can
go to the command window, set
the Current Directory to the directory in which the files was saved, and then
type the files name (without the .m suffix). This causes MATLAB to
perform the commands in the file. One can also cause MATLAB to execute
the commands in the file by hitting F5 while in the editor window. For the
time being we will make use of the editor to save our work and to do the
work in a way that makes it easy to correct mistakes and to print the code
that we have written. Please make sure to save what you are working on at
regular intervals. Comments starting a line with a percent sign tells
MATLAB that that line is a comment. As with all programming languages,
it is very important to comment your code. MATLAB has a help command.
Typing help com_name causes MATLAB to respond with information about
5
8/8/2019 Simulation Lab 4-06-2010
6/88
the command. If one writes a file, places comments at the very beginning of
the file, and types help filename, MATLAB prints the comments that appear
at the beginning of the file. This allows the user to expand the MATLAB
help facility.
Defining a Transfer Function Object:
To define a transfer function object that corresponds to a transfer function
that is rational functiona function that is the quotient of polynomials one
gives MATLAB the command tf (num, den). The vector num contains the
coefficients of the numerator polynomial and the vector den contains the
coefficient of the denominator polynomial. The first element of each vector
is the coefficient of the highest power in the polynomial, and each element
afterwards corresponds to the next lower power of s. Suppose that one has a
system for which G(s) = 1/0.1s + 1
.Giving MATLAB the command G = tf([1],[0.1 1]) cause MATLAB to
respond with Transfer function: 1 / s + 1. Analyzing a Transfer Function
There are many ways that MATLAB can help analyze a transfer function.
Supposing that we have defined the transfer function object G as we did
above. To examine Gs impulse response, one need only give MATLAB the
command impulse (G).To examine the step response all one need do is give
MATLAB the command step(G).By using the magnifying glasses in the
toolbar above the figures, it is possible to zoom in on parts of a figure or to
zoom out from parts of a figure. MATLAB makes it easy to plot Bode plots
as well. The command bode(G) will cause MATLAB to produce the Bode
plots .
Matlab is an interpreted language that means that it translates the command
into machine code when it is executed. If something is changed, it means
6
8/8/2019 Simulation Lab 4-06-2010
7/88
that all consecutive commands must be updated to contain the correct
values. Start by defining a vector s:
>> s= [1,3,5,9,34,32,11] Matlab writes the vector to the screen when return
is hit. To avoid this writing, type a semicolon after the expression, for
example:
>> s2=s.^2;
You can see the contents of s2 by typing
>> s2
Now we want to change the vector s. Set it to
>> s= [3, 23, 66, 43, 11]
Note that the vector s2 has not changed after this command:
>> s2
To update s2 with the new s vector, you must type it again (Use the arrow
keys (up/down) to go backwards and forwards in the command buffer.):
>> s2=s.^2;
And so the correct value is there:
>> s2
Online demo and help: A short introduction to Matlab is retrieved by
typing,
>> intro
and further demonstrations are available through
>> demo
7
8/8/2019 Simulation Lab 4-06-2010
8/88
Try a few of the available demonstrations. All functions in Matlab has a
brief on-line documentation. It is accessed by typing help . For
instance, the functionality of eig is retrieved by typing:
>> help eig
Continue to examine how the following functions work: dir, save, lookfor,
zeros, ones, rand, sin, exp, factor, det, max, min, sum, log, log10, ode23,
datafun, conv.
Variables:
If you do a lot of computing with Matlab, sometimes you would bereminded what variables you actually have used and defined. Then you can
make use of the the two commands below. To see the variables that are
defined you can type:
>> who
To receive more information about the variables type
>> whos
What is the information displayed? Now, if you want to remove a variable
you can use clear:
>> clear s
Check again what variables you have:
>> who
On the other hand, if you need to remove all variables type
>> clear
8
8/8/2019 Simulation Lab 4-06-2010
9/88
Matrices:
Matlab stand for Matrix Laboratory. The whole code of Matlab is made such
that it is very fast if the computing is defined as matrices and vectors. Here
is an examples of a matrix m1 and a vector v1:
Type:
>> m1=[6 8 10 13; 28 0 6 1;1 3 29 31]
>> v1=[3;18;1]
We use these to calculate the product m2=m1T v1:
>> m2=m1'*v1;
Is the result correct? Check! Think how you would write this in a
conventional programming language. Which way do you prefer? Sub-
matrices can be extracted from readily defined matrices. To choose the first
and the last column and the middle row from m1, one writes
>> m1(2,[1,4])
If a whole row or column is needed, for instance
it is possible to use ':'
>> m1(:,[1,4])
Use this technique on m1 and v1 to calculate the product
Operators:
The Matlab language has its own syntax that has to be learnt. We have
already seen some of the operators between matrices and vectors. Matlabcan however act on matrices or on the separate elements in the matrices.
This is decided by which operator is used. See all operators that are available
by typing
>> help ops
9
8/8/2019 Simulation Lab 4-06-2010
10/88
The most important matrix operators are:
multiplication *
division/ and \, (can also be used for solutions of over estimated
systems)addition +
subtraction -
power ^
transpose ' and .', (the former is complex conjugate transpose)
Here is an example how to use some of the operators:
>> m1'*v1+1-[1;2;3;4]
Dotted operators:
Some of the operators on separate elements are preceded by a dot (.), other
are the same as for the matrix operators, i.e. there is no difference between
matrix and element operators such as addition. The element by element
operators are for instance:
multiplication .*
division ./
addition +
subtraction -
power .^
An example how to use them:
>> v1.*[1;2;3]+[4;5;6].^3
Exercise: Calculate the 5th power of the matrix
10
8/8/2019 Simulation Lab 4-06-2010
11/88
Then find the answer to 15, 25, 35, 45, 55, 65, 75, 85, 95 by applying the array
operator (dotted operator) on m3. It is important to know the difference
between array operators and matrix operators!
Matlab functions:
The functions that are available in Matlab are of built-in and m-file types.
Matlab has whole libraries of built in functions, for instance: sum, sin, sign,
abs, gamma, besselj. There are also ready written functions as some
functions provided by Mathworks for an exchange of a lot of money, e.g.
functions for signal processing (signal), partial differential equations (pde),fuzzy logic (fuzzy), system identification (ident), control (control),
optimisation (optim) etc. Try them out by typing help and a word in brackets
above.
>> help signal
Matlab also allows for users to write their own functions. A function works
as a subroutine, where a script is used instead of typing in the command
window. Matlab functions are written in text files with the extension .m,
called m-files. During the following Matlab exercises you will write your
own functions in .m files. An example is the function myfunc given below.
The sign % indicates a comment line. myfunc shows how different signal
processing operations (convolutions, Fourier transforms, etc.) are
implemented in Matlab with one single command.
function r = myfunc(x,y,s)
% MYFUNC is my own-made Matlab function.
% MYFUNC is my first attempt to make a Matlab function.
% It is used by typing:
11
8/8/2019 Simulation Lab 4-06-2010
12/88
% r=myfunc(x,y,s)
% where x, y and s are inputs
% and r is output.
z=conv(x,y);
r=filter (z,y,s);
R=fft(r);
S=fft(s);
l=length(r);
subplot(2 1 1)
plot(abs(S),'b')
hold on
plot(abs(R),'r')
hold off
title('Result of calculations')
ylabel('Absolute values of R, S')
subplot(2 1 2)
plot(s)
hold on
plot(r,'r')
hold off xlabel('time')
title('Input / output signals')
Now type the program in a text file called myfunc.m and save it in your
folder 'CSmatlab'. Use the matlab-editor, evoked by [File-->New-->M-file].
Then test the program by typing:
12
8/8/2019 Simulation Lab 4-06-2010
13/88
>> x=[0.1238 , 0.3715 , 0.3715 , 0.1238];
>> y=[1.0000 , -1.1619 , 0.6959 , -0.1378];
>> s=randn(256,1);
>> r=myfunc(x,y,s);
This is just an example how various complex signal processing operations
such as Fourier Transforms, convolustions etc. can be performed by means
of one simple Matlab command.
Logic:
Normal logic functions included in most programming languages are also
present in Matlab: for end, if else end, relations: > < >= > for k=1:5
y(k)=31^k;
end
>> y
But since Matlab is made for matrix manipulations the above example is
faster to calculate by writing:
>> y=31. ^ [1:5]
Plotting:
Create a vector that contains data of a sinusoid:
>> k=0:39;
13
8/8/2019 Simulation Lab 4-06-2010
14/88
>> s=sin(2*pi*k/40);
Plot this discrete signal with the command
>> stem(k,s)
The signal s could also be thought of as a discrete representation of a
analogue signal. Then we prefer to plot it with another function. First we
create a time vector from 0 to 40 ms.
>> t=(0:39)/1000; % t=time [ms]
>> plot(t,s)
If a logarithmic scale is desired, the following commands can also be used:
loglog, semilogy, semilogx.
DATA PRESENTATION
MATLAB provides a variety of functions for displaying data as 2-D and 3-D
plots of curves and 3-D mesh surface plots, as well as functions for
annotating these graphs. On-line help for each of the commands shown
below is available by typing help command name or doc command
name at the MATLAB prompt.
2-D PLOTS:
The following list summarizes the functions that produce basic line plots of
data. These functions differ only in the way they shape and scale the plot
axes. Each accepts arguments in the form of vectors or matrices and
automatically scales the axis to accommodate the data range.
plot(x,y) Generates a linear plot ofx versus y
errorbar(x,y,e) Generates a linear plot ofx versus y with with error bars
that are symmetric about y and are 2*e(i) long
semilogx(x,y) Generates a plot ofx versus y using a logarithmic scale
for x
14
8/8/2019 Simulation Lab 4-06-2010
15/88
semilogy(x,y) Generates a plot ofx versus y using a logarithmic scale
for y
loglog(x,y) Generates a plot ofx vs. y using a logarithmic scale for x and y
polar(theta,r) Generates a polar plot of angles theta(in rads) versus
magnitudes r
bar(x,y) Generates a bar graph ofy at locations specified by x
hist(y,nb) Generates a histogram of data in vectory in nb number of bins
stairs(x,y) Generates a stair graph of y at locations specified by equally
spaced x
stem(x,y) Generates a discrete impulse plot ofy at locations specified by x
rose(theta,nb) Generates a angle histogram for angles in theta in nb
number of bins
compass(z) Generates a plot that displays the angle and magnitude of the
complex elements ofz as arrows emanating from the origin
quiver(x,y,dx,dy) Generates a plot that displays little arrows at every (x,y)
pair where dx and dy determine the direction and magnitude of the arrows
subplot(n,m,p) Splits the graphics window into a n-by-m matrix of plots
where p will be next window used for a plot command.
PLOTTING OPTIONS
plot_command(x,y,w,z) Generates two plots on the same axes
plot_command(x,y,indicator) Establishes line or marker style and color
15
8/8/2019 Simulation Lab 4-06-2010
16/88
Data Presentation: INDICATORS:
line type indicator point type indicator color indicator
solid - point . red r
dashed -- plus + yellow y
dotted : star * green g
dashdot -. circle O blue b
x-mark x magenta m
cyan c
white w
black k
SCALING
axis(axis) Freezes the current axis scaling for subsequent plots
axis(v) v is a 4-element vector containing [xmin, xmax, ymin, ymax]
axis square Specifies the aspect ratio to be square
axis auto Specifies the aspect ratio to return to the default
hold Freezes the current axis scaling and plot for subsequent plots to share
(another way to make multiple plots on the same graph) The second call to
hold releases the current axis.
ANNOTATION
The following list summarizes the commands for adding annotation to plots.
title(text) Writes the text string as a title at the top of the
current plot
16
8/8/2019 Simulation Lab 4-06-2010
17/88
xlabel(text) Writes the text string beneath the x-axis on the current plot
ylabel(text) Writes the text string beside the y-axis on the current plot
legend (str1,...) Puts a legend on the current plot using the specified
strings as labels
text(text) Writes the text string at the point specified by (x,y) on the
current plot
gtext(text) Writes the text string at the point specified by a mouse click
grid Adds grid lines to the current plot
SCREEN CONTROL
shg Show graph window
clg Clear graph window
figure Create a graph window
delete Delete a graph window
axes Control the graph axis properties
gcf Get current figure handle
gca Get current axis handle
set Change object property values
get Get object property values
Experiment.1
Aim: Write a MATLAB program to perform the Basic Operations onMatrices.
% Basic Matrix Operationsclc;
17
8/8/2019 Simulation Lab 4-06-2010
18/88
close all;
% Addition of 2 matrices
A = [ 1 2 3; 3 4 5; 6 7 8];B = [ 1 2 3; 2 4 7; 3 5 8];
C=A+B
% Subtraction of 2 MatricesD=A-B
% Multiplication of 2 Matrices
E=A*B% Division of 2 Matrices
F=A/B
% Inverse of 2 Matrices
G=inv(A)%Element by Element Multiplication
H=A.*B
% Transpose of matrices
A_transpose=A'B_transpose=B'
% DeterminantK=det(A)
L=det(B)
% Eigen Values and Eigen Vectors
[V,E]=eig(A)[V,E]=eig(B)
Output:
C=
2 4 6
5 8 129 12 16
D =
0 0 01 0 -2
3 2 0
E =
14 25 4126 47 77
44 80 131
F =
1.0000 0 0
1.0000 -2.0000 2.00001.0000 -5.0000 5.0000
G =
1.0e+015 *
-2.7022 4.5036 -1.8014
18
8/8/2019 Simulation Lab 4-06-2010
19/88
5.4043 -9.0072 3.6029
-2.7022 4.5036 -1.8014
H =1 4 9
6 16 35
18 35 64A_transpose =
1 3 6
2 4 73 5 8
B_transpose =
1 2 32 4 5
3 7 8
K =
0L = 1
V =-0.2656 -0.7444 0.4082
-0.4912 -0.1907 -0.8165
-0.8295 0.6399 0.4082
E =14.0664 0 0
0 -1.0664 0
0 0 -0.0000V =
-0.2797 -0.2360 - 0.4332i -0.2360 + 0.4332i
-0.6148 0.7650 0.7650-0.7374 -0.3864 + 0.1486i -0.3864 - 0.1486i
E =
13.3063 0 00 -0.1531 + 0.2274i 0
0 0 -0.1531 - 0.2274i
Experiment.2
Aim: Write a MATLAB program to generate Various Signals and Sequences(Periodic and Aperiodic) such as Unit Impulse, Unit Step, Square, Sawtooth, Triangular, Sinusoidal, Ramp, and Sinc function.
% to plot continuous time signals%
19
8/8/2019 Simulation Lab 4-06-2010
20/88
clear all
t=-1:.01:1;
x1=sin(2*pi*1.5*t);subplot(2,2,1), plot(t,x1);
xlabel('.........> t ');
ylabel('x1(t)');title(' sinusoidal signal');
% to plot an exponential signal%
x2=exp(-2*t);subplot(2,2,2), plot(t,x2);
xlabel('.........> t ');
ylabel('x2(t)');
title(' exponential signal');
% to plot sawtooth signal %
t1=-20:0.01:20;
x3=sawtooth(t1);subplot(2,2,3), plot(t1,x3);
xlabel('.........> t1 ');ylabel('x3(t)');
title(' swatooth signal');
%to plot a square signal5t1=-20:0.01:20;
x4=square(t1);
subplot(2,2,4), plot(t1,x4);xlabel('.........> t1 ');
ylabel('x4(t)');
title(' square signal');clear all
% T0 PLOT A SINC FUNCTION %t1=-20:0.01:20;
x5=sinc(t1/2);
subplot(2,2,1), plot(t1,x5);
xlabel('.........> t1 ');ylabel('x5(t)');
axis([ -20 20 -1.5 1.5 ] )
title(' SINC FUNCTION');
% TO PLOT A RECTANGULAR PULSE%
x6=rectpuls(t1/10);subplot(2,2,2), plot(t1,x6);
xlabel('.........> t1 ');
ylabel('x6(t)');
axis([ -20 20 -1.5 1.5 ] )
20
8/8/2019 Simulation Lab 4-06-2010
21/88
title(' RECTANGULAR PULSE');
% TO PLOT A TRIANGULAR PULSE%
x7=tripuls(t1/10);subplot(2,2,3), plot(t1,x7);
xlabel('.........> t1 ');
ylabel('x7(t)');axis([ -20 20 -1.5 1.5 ] )
title(' TRIANGULAR PULSE');
%TO PLOT A SIGNUM FUNCTION%
x8=sign(t1/3);
subplot(2,2,4), plot(t1,x8);xlabel('.........> t1 ');ylabel('x8(t)');axis([ -20 20 -1.5 1.5 ] )
title(' SIGNUM FUNCTION');
Output Waveforms:
21
8/8/2019 Simulation Lab 4-06-2010
22/88
22
8/8/2019 Simulation Lab 4-06-2010
23/88
23
8/8/2019 Simulation Lab 4-06-2010
24/88
% TO GENERATE A UNIT STEP SEQUENCE%
N=31;
x1=ones(1,N);n=0:1:N-1;
subplot(2,2,1), stem(n,x1);
xlabel('n ');ylabel('x1(n)');
title('UNIT STEP SEQUENCE');
% TO GENERATE A SINUSOIDAL SEQUENCE %
x2=2*cos(.1*pi*n);
subplot(2,2,2), stem(n,x2);
xlabel('n ');ylabel('x2(n)');
title('SINUSOIDAL SEQUENCE');
% TO GENERATE A EXPONENTIAL SEQUENCE%x3=.6.^(n) ;
subplot(2,2,3), stem(n,x3);xlabel('n ');
ylabel('x3(n)');
title('EXPONENTIAL SEQUENCE');
% TO GENERATE A UNIT IMPULSE SEQUENCE %
n=-4:1:4;
x4=[zeros(1,4),ones(1,1),zeros(1,4);]subplot(2,2,4), stem(n,x4);
xlabel('n ');
ylabel('x4(n)');title('UNIT IMPULSE SEQUENCE');
24
8/8/2019 Simulation Lab 4-06-2010
25/88
Output Waveforms:
25
8/8/2019 Simulation Lab 4-06-2010
26/88
% TO GENERATE A UNIT RAMP SEQUENCE %
n=0:1:10;x1=n ;
subplot(3,1,1), stem(n,x1);
xlabel('n ');ylabel('x1(n)');
title('UNIT RAMP SEQUENCE');
%% TO GENERATE A UNIT STEP SEQUENCE%
n=-4:1:4;
x2=[zeros(1,4),ones(1,5)];
subplot(3,1,2), stem(n,x2);xlabel('n ');
ylabel('x2(n)');
title('UNIT STEP SEQUENCE');
% TO GENERATE A SINUSOIDAL SEQUENCE %
n=-20:.25:20x3=2*sin(.5*pi*n);
subplot(3,1,3), stem(n,x3);
xlabel('n ');
ylabel('x3(n)');title('SINUSOIDAL SEQUENCE');
26
8/8/2019 Simulation Lab 4-06-2010
27/88
Output Waveforms:
27
8/8/2019 Simulation Lab 4-06-2010
28/88
Experiment.3.
Aim: Write a MATLAB program to perform Operations on Signals andSequences such as Addition, Multiplication, Scaling, Shifting, Folding,Computation of Energy and Average Power.
% ADDTION OF TWO SEQUENCES %
n=0:1:3;
x=[1,2,2,3];n1=length(x);
subplot(2,2,1),stem(n,x);
xlabel('n'); ylabel('input sequence');
% INPUT SEQUENCE2 %
n=0:1:3;
y=[1,6,4,3];
n2=length(y);subplot(2,2,2),stem(n,y);
xlabel('n'); ylabel('input sequence');% ADDITION OF x and y %
n=0:1:6;
R1=x+y;
subplot(2,2,3), stem(R1);xlabel('n'); ylabel('ADDITION OF X and Y ');
28
8/8/2019 Simulation Lab 4-06-2010
29/88
Output Waveforms:
29
8/8/2019 Simulation Lab 4-06-2010
30/88
% Operations on Signals and Sequences%
% ADDITION OF TWO SINUSOIDAL SIGNALS %
clc;t=0:.01:pi;
y1=sin(2*pi*t);
subplot(3,1,1);plot(t,y1);
title('sinusoidal signal 1');
y2=cos(3*pi*t);subplot(3,1,2);
plot(y2);
title('sinusoidal signal 2');
h=y1+y2;subplot(3,1,3);
plot(h);
title('ADDITION OF TWO SINE WAVES');
30
8/8/2019 Simulation Lab 4-06-2010
31/88
Output Waveforms:
31
8/8/2019 Simulation Lab 4-06-2010
32/88
% OPERATIONS ON SIGNALS %
% TIME SCALING ,TIME SHIFTING %clear all;
tmin=-15; tmax=20;
t=tmin:.1:tmax;y0=y(t);
y1=y(t+4);
y2=2*y(t-3);y3=y(2*t);
y4=y(2*t-3);
y5=y(t/2);
ymax=max([max(y0),max(y1),max(y2),max(y3),max(y4),max(y5)]);ymin=min([min(y0),min(y1),min(y2),min(y3),min(y4),min(y5)]);
subplot(3,2,1),plot(t,y0);
xlabel('t'),ylabel(y0);
axis([tmin tmax ymin ymax]);subplot(3,2,2),plot(t,y1);
xlabel('t'),ylabel(y1);axis([tmin tmax ymin ymax]);
subplot(3,2,3),plot(t,y2);
xlabel('t'),ylabel(y2);
axis([tmin tmax ymin ymax]);subplot(3,2,4),plot(t,y3);
xlabel('t'),ylabel(y3);
axis([tmin tmax ymin ymax]);subplot(3,2,5),plot(t,y4);
xlabel('t'),ylabel(y4);
axis([tmin tmax ymin ymax]);subplot(3,2,6),plot(t,y5);
xlabel('t'),ylabel(y5);
axis([tmin tmax ymin ymax]);
function x=y(t);
x1=t+5;x2=11+4*t;
x3=24-9*t;
x4=t-6;x=x1.*(-5
8/8/2019 Simulation Lab 4-06-2010
33/88
Output Waveforms:
33
8/8/2019 Simulation Lab 4-06-2010
34/88
Experiment 4.
Aim: Write a MATLAB program to Find the Even and Odd parts ofSignal/Sequence and Real and Imaginary Parts of Signal.
% program to plot function y(t),y(-t),odd and even parts of y(t)% consider y.m file which acts as function here
clear all;
close all;clc;
%generate given signal
nmin=-10;
nmax=10;n=nmin:1:nmax;
% given signal
y0=y(n);
%time reversal of signaly1=y0(end:-1:1);
ymax=max([max(y0),max(y1)]);ymin=min([min(y0),min(y1)]);
subplot(2,2,1),plot(n,y0);
xlabel('\itt');ylabel('y({\itt})');
subplot(2,2,2),plot(n,y1);xlabel('\itt');ylabel('y({-\itt})');
% Even part of a signal
ye=(y0+y1)/2;% odd part of a signal
yo=(y0-y1)/2;
subplot(2,2,3),plot(n,ye);xlabel('\itt'),ylabel('y_e({\itt})');
subplot(2,2,4),plot(n,yo);
xlabel('\itt'),ylabel('y_o({\itt})');
function x=y(t)
x1=t+5;x2=11+(4*t);x3=24-(9*t);x4=t-6;
x=x1.*(-5
8/8/2019 Simulation Lab 4-06-2010
35/88
Output Waveforms :
35
8/8/2019 Simulation Lab 4-06-2010
36/88
Experiment 5.
Aim: Write a MATLAB program to find the Convolution between Signalsand Sequences.
% Convolution of two given sequences %
clear allx=[1,2,1,2,1,3,2];
N1=length(x);
n=0:1:N1-1;
subplot(2,2,1),stem(n,x);xlabel('n'),ylabel('x(n)');
title('input sequence of x(n)');
h=[1,-1,2,-2,1,1];
N2=length(h);n1=0:1:N2-1;
subplot(2,2,2),stem(n1,h);xlabel('n'),ylabel('h(n)');
title('impulse sequence of x(n)');
y=conv(x,h)
n2=0:1:N1+N2-2;subplot(2,1,2),stem(n2,y);
xlabel('n'),ylabel('y(n)');
title('Convolution of two sequences of x(n) and h(n)');
36
8/8/2019 Simulation Lab 4-06-2010
37/88
Output Waveforms:
37
8/8/2019 Simulation Lab 4-06-2010
38/88
% Convolution of 2 signals %clc;
t=0:.01:pi;
y1=sin(2*pi*t);subplot(3,1,1);
plot(t,y1);
y2=cos(3*pi*t);subplot(3,1,2);
plot(y2);
h=conv(y1,y2);
subplot(3,1,3);plot(h);
Output Waveforms:
38
8/8/2019 Simulation Lab 4-06-2010
39/88
Experiment 6.
Aim: Write a MATLAB program to find the Auto Correlation and CrossCorrelation between Signals and Sequences.
% TO GENERATE THE AUTO CORRELATION and CROSS CORRELATION%% INPUT SEQUENCE1 %
n=0:1:3;
x=[1,2,2,3];n1=length(x);
subplot(2,2,1),stem(n,x);
xlabel('n'); ylabel('input sequence');
% INPUT SEQUENCE2 %
n=0:1:3;y=[1,6,4,3];
n2=length(y);
subplot(2,2,2),stem(n,y);
xlabel('n');ylabel('input sequence');
% AUTO CORRELATION OF x and y %
n=0:1:6;R1=xcorr(x,x);
subplot(2,2,3), stem(R1);
xlabel('n'); ylabel('ACR sequence');
% CROSS CORRELATION OF x and y %
n=0:1:6;
R2=xcorr(x,y);
subplot(2,2,4), stem(R2);xlabel('n');
ylabel('CCR sequence');
39
8/8/2019 Simulation Lab 4-06-2010
40/88
Output Waveforms:
40
8/8/2019 Simulation Lab 4-06-2010
41/88
% ACR and CCR OF TWO SINUSOIDAL SIGNALS%
% TO GENERATE A SINUSOIDAL SEQUENCE %n=-20:.25:20
x1=2*sin(.5*pi*n);
subplot(4,1,1), stem(n,x1);xlabel('n ');
ylabel('x1(n)');
title('SINUSOIDAL SIGNAL1');% TO GENERATE A SINUSOIDAL SEQUENCE %
x2=2*cos(.1*pi*n);
subplot(4,1,2), stem(n,x2);
xlabel('n ');ylabel('x2(n)');
title('SINUSOIDAL SIGNAL2');
% AUTO CORRELATION OF x1 and x2 %
n=0:1:6;R1=xcorr(x1,x2);
subplot(4,1,3), stem(R1);xlabel('n'); ylabel('ACR OF X1 and X2');
% CROSS CORRELATION OF x and y %
n=0:1:6;
R2=xcorr(x1,x2);subplot(4,1,4), stem(R2);
xlabel('n'); ylabel('CCR OF X1 and X2');
41
8/8/2019 Simulation Lab 4-06-2010
42/88
Output Waveforms:
42
8/8/2019 Simulation Lab 4-06-2010
43/88
Experiment 7.
Aim: Write a MATLAB program to compute the unit sample, unit step andsinusoidal response of the given LTI system and verifying its physical
realiazability and stability properties.
% IMPULSE RESPONSE OF A DIGITAL FILTER %
clear all;
b=input('enter the numerator coefficients');
a=input('enter the denominator coefficients');
[H,T]=impz(b,a); stem(T,H);xlabel('n'),ylabel('h(n)');
title('IMPULSE RESPONSE OF DIGITAL FILTER');
Output: H = 1.000 ,.7,.37, .1750, .0781, .0337, .0142, .0059, .0024, .0010 T= 0 1 2 3 4 5
6 7 8 9Output Waveforms:
43
8/8/2019 Simulation Lab 4-06-2010
44/88
%IMPULSE RESPONSE OF A ANALOGFILTER %
clear all;close all;
clc;
% T=0:.01:200;b=input('enter the numerator coefficients');
a=input('enter the denominator coefficients');
[H,T]=impulse(b,a); plot(H);
xlabel('t'), ylabel('h(t)');title('IMPULSE RESPONSE OF ANALOG FILTER');
Output Waveforms:
44
8/8/2019 Simulation Lab 4-06-2010
45/88
%STEP RESPONSE OF A ANALOGFILTER %
close all;
clc;b=input('enter the numerator coefficients');
a=input('enter the denominator coefficients');
[H]=step(b,a);plot(H);
xlabel('t')
ylabel('s(t)')
title('STEP RESPONSE OF ANALOG FILTER');
Output Waveforms:
45
8/8/2019 Simulation Lab 4-06-2010
46/88
% SINUSOIDAL RESPONSE OF LINEAR SYSTEM %
clear all;
s=tf('s');g=(s+1)/(s^2+5*s+6);
t=0:0.1:15;
u=sin(t);lsim(g,u,t);
Output Waveforms:
46
8/8/2019 Simulation Lab 4-06-2010
47/88
% EXPONENTIAL RESPONSE OF LINEAR SYSTEM %
clear all;
s=tf('s');g=(s+1)/(s^2+5*s+6);
t=0:0.1:15;
u=exp(-3*t);lsim(g,u,t);
Output Waveforms:
47
8/8/2019 Simulation Lab 4-06-2010
48/88
Experiment 8.
Aim: Write a MATLAB program to verify the Gibbs phenomenon.
% plot square wave and verify Gibbs phenomena using first 10 terms of Fourier series
clear all;
T=input('enter the time period of the square wave\n');n1=input('enter the number of cycles to be plotted\n');
n=input('enter number of harmonics to be considered apart from dc\n');
k=n1*T/2;
i=0;for t=-k:k/100:k
x=0;
for j=1:2:(2*n-1)
xnew=x+(4*(cos((t*2*pi*j/T)-(pi*floor(j/2))))/(j*pi));x=xnew;
endi=i+1;
p(:,i)=x;
end
t=-k:k/100:k;plot(t,p);
48
8/8/2019 Simulation Lab 4-06-2010
49/88
Output Waveforms :
49
8/8/2019 Simulation Lab 4-06-2010
50/88
Experiment 9.
Aim: Write a MATLAB program to verify the Sampling Theorem.
% Sampling Theorem %
clc;clear all;
close all;
t=-100:.01:100;fm=.02;
x=cos(2*pi*t*fm);
subplot(2,2,1),plot(t,x);
xlabel('time in sec'),ylabel('x(t)');title('continous time signal');
fs1=.02;
n=-2:2;
x1=cos(2*pi*fm*n/fs1);subplot(2,2,2),stem(n,x1);
hold onsubplot(2,2,2);
plot(n,x1);
title('discrete time signal x(n) with fs2fm');
xlabel('n'),ylabel('x(n)');
50
8/8/2019 Simulation Lab 4-06-2010
51/88
Output Waveforms:
51
8/8/2019 Simulation Lab 4-06-2010
52/88
Experiment 10.
Aim: Write a MATLAB program to locate the Zeros and Poles and plottingthe Pole-Zero maps in S-plane and Z-plane for the given transfer function.
% POLE-ZERO PLOT %
close all; clc;
b=input ('enter the numerator coefficients');a=input ('enter the denominator coefficients');
zplane (b, a); title ('POLE-ZERO PLOT');
Output: enter the numerator coefficients [1 5]enter the denominator coefficients [1 3 2]
Output Waveform:
52
8/8/2019 Simulation Lab 4-06-2010
53/88
Experiment 11.
Aim: Write a MATLAB program to verify the Linearity, Time Invariance and
Stability of a Discrete time System.
% VERIFICATION OF LINEARITY OF DISCRETE SYSTEM %
n=0:40; a=2; b=-3;
x1=cos(2*pi*0.1*n);
x2=cos(2*pi*0.4*n);
x=a*x1+b*x2;
ic=[0 0];
num=[2.2403 2.4908 2.2403];
den=[1 -0.4 0.75];
y1=filter(num,den,x1,ic);
y2=filter(num,den,x2,ic);
y=filter(num,den,x,ic);yt=a*y1+b*y2;
d=y-yt;
subplot(3,1,1), stem(n,y); grid
title('LINEARITY OF DISCRETE TIME SYSTEM ');
subplot(3,1,2), stem(n,yt); grid
subplot(3,1,3), stem(n,d); grid
53
8/8/2019 Simulation Lab 4-06-2010
54/88
Output Waveforms:
54
8/8/2019 Simulation Lab 4-06-2010
55/88
% VERIFICATION OF TIME INVARIANCE OF DTS %
n=0:40;D=10;x=3*cos(2*pi*0.1*n)-2*cos(2*pi*0.4*n);
xd=[zeros(1,D) x];
num=[2.2403 2.4908 2.2403];den=[1 -0.4 0.75];
ic=[0 0];
y=filter(num,den,x,ic)yd=filter(num,den,xd,ic)
d=y-yd(1+D:41+D);
subplot(3,1,1),stem(y),grid;
title('TIME INVARIANCE OF DTS' );subplot(3,1,2),stem(yd),grid;
subplot(3,1,3),stem(d),grid;
55
8/8/2019 Simulation Lab 4-06-2010
56/88
% TO CHECK THE STABILITY OF THE SYSTEM %
num=[1 0.8];
den=[1 1.5 .9];
N=200;h=impz(num,den,N+1);
sum=0;
n=0:N;
for k=1:N+1
if abs(h(k))
8/8/2019 Simulation Lab 4-06-2010
57/88
Output Waveforms:
57
8/8/2019 Simulation Lab 4-06-2010
58/88
Experiment 12.
Aim: Write a MATLAB program to generate the Gaussian noise (Real and
Complex), computation of mean, M.S value and its skew, and PSD ,
Probability Distributation function.
% Generation of Gaussian Noise and its mean %
clear;
N=100;
sigw1=sqrt(4);
sigw2=sqrt(9);
rho=-0.4;
x1=rand(1,N);
x2=rand(1,N);
y1=sqrt(-2*log(x1)).*cos(2*pi*x2);
y2=sqrt(-2*log(x1)).*sin(2*pi*x2);
t11=sigw1;
t21=rho*sigw2;
t22=sigw2*sqrt(1-rho^2);w1=t11*y1;
w2=t21*y1+t22*y2;
wmean=[mean(w1) mean(w2)];
wcov=[cov(w1,1) cov(w2,1)];
tmp=corrcoef(w1,w2);
rho_hat=tmp(2,1);
cov_err=100*(sqrt(wcov)-([sigw1 sigw2].^2))./...
([sigw1 sigw2].^2)
rho_err=100*(rho_hat-rho)./rho
58
8/8/2019 Simulation Lab 4-06-2010
59/88
Output:
cov_err =
-50.0337 -68.3450
rho_err =
-10.2492
wmean =
0.4082 -0.3190
59
8/8/2019 Simulation Lab 4-06-2010
60/88
Experiment 13.
Aim: Write a MATLAB program to obtain the Fourier transform of the signal
using Fast Fourier Transform.
% FOURIER TRANSFORM OF A SEQUENCE USING FFT %
N=50;
xn=[1 3 5 8 2 8 9 3 9 7];
subplot(3,1,1); stem(xn);
title('Fourier Transform of the sequence');
Xk=fft(xn,N);
k=0:1:N-1;
subplot(3,1,2); stem(k,abs(Xk));
xlabel('k');
ylabel('Magnitude of Xk');
subplot(3,1,3); stem(k,angle(Xk));
xlabel('k');
ylabel('arg(Xk)');
60
8/8/2019 Simulation Lab 4-06-2010
61/88
Output Waveform:
61
8/8/2019 Simulation Lab 4-06-2010
62/88
1. MATLABBasics
MATLAB is started by clicking the mouse on the appropriate icon and is ended by typing
exit or by using the menu option. After each MATLAB command, the "return" or "enter"key must be depressed.
A. Definition of Variables
Variables are assigned numerical values by typing the expression directly, for example,
typing
a = 1+2
yields: a = 3
The answer will not be displayed when a semicolon is put at the end of an expression, for
example type a = 1+2;.
MATLAB utilizes the following arithmetic operators:
+ addition- subtraction* multiplication/ division^ power operator' transpose
A variable can be assigned using a formula that utilizes these operators and eithernumbers or previously defined variables. For example, since a was defined previously,
the following expression is valid
b = 2*a;
To determine the value of a previously defined quantity, type the quantity by itself:
b
yields: b = 6
If your expression does not fit on one line, use an ellipsis (three or more periods at theend of the line) and continue on the next line.
c = 1+2+3+...5+6+7;
62
8/8/2019 Simulation Lab 4-06-2010
63/88
There are several predefined variables which can be used at any time, in the same manner
as user-defined variables:
i sqrt(-1)j sqrt(-1)pi 3.1416...
For example,
y= 2*(1+4*j)
yields: y = 2.0000 + 8.0000i
There are also a number of predefined functions that can be used when defining a
variable. Some common functions that are used in this text are:
abs magnitude of a number (absolute value for real numbers)
angle angle of a complex number, in radianscos cosine function, assumes argument is in radianssin sine function, assumes argument is in radiansexp exponential function
For example, with y defined as above,
c = abs(y)
yields: c = 8.2462
c = angle(y)
yields: c = 1.3258
With a=3 as defined previously,
c = cos(a)
yields: c = -0.9900
c = exp(a)
yields: c = 20.0855
Note that exp can be used on complex numbers. For example, with y =2+8i as defined above,
c = exp(y)
63
8/8/2019 Simulation Lab 4-06-2010
64/88
yields: c = -1.0751 + 7.3104i
which can be verified by using Euler's formula:
c = exp(2)cos(8) + je(exp)2sin(8)
back to list of contents
B. Definition of Matrices
MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices.
Therefore, vector and matrix operations are as simple as common calculator operations.
Vectors can be defined in two ways. The first method is used for arbitrary elements:
v = [1 3 5 7];
creates a 1x4 vector with elements 1, 3, 5 and 7. Note that commas could have been used
in place of spaces to separate the elements. Additional elements can be added to the
vector:
v(5) = 8;
yields the vectorv = [1 3 5 7 8]. Previously defined vectors can be used to define a newvector. For example, with v defined above
a = [9 10];
b = [v a];
creates the vectorb = [1 3 5 7 8 9 10].
The second method is used for creating vectors with equally spaced elements:
t = 0:.1:10;
creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number
defines the increment. If only two numbers are given, then the increment is set to a
default of 1:
k = 0:10;
creates a 1x11 vector with the elements 0, 1, 2, ..., 10.
Matrices are defined by entering the elements row by row:
M = [1 2 4; 3 6 8];
64
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
65/88
creates the matrix
There are a number of special matrices that can be defined:
null matrix: M = [ ];nxm matrix of zeros: M = zeros(n,m);nxm matrix of ones: M = ones(n,m);nxn identity matrix: M = eye(n);
A particular element of a matrix can be assigned:
M(1,2) = 5;
places the number 5 in the first row, second column.
In this text, matrices are used only in Chapter 12; however, vectors are used throughout
the text. Operations and functions that were defined for scalars in the previous section
can also be used on vectors and matrices. For example,
a = [1 2 3];b = [4 5 6];c = a + b
yields:
c = 5 7 9
Functions are applied element by element. For example,
t = 0:10;x = cos(2*t);
creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10.
Operations that need to be performed element-by-element can be accomplished by
preceding the operation by a ".". For example, to obtain a vectorx that contains theelements of x(t) = tcos(t) at specific points in time, you cannot simply multiply the vectort with the vectorcos(t). Instead you multiply their elements together:
t = 0:10;x = t.*cos(t);
back to list of contents
65
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
66/88
C. General Information
Matlab is case sensitive so "a" and "A" are two different names.
Comment statements are preceded by a "%".
On-line help for MATLAB can be reached by typinghelp for the full menu or typinghelp followed by a particular function name or M-file name. For example, help cosgives help on the cosine function.
The number of digits displayed is not related to the accuracy. To change the format of the
display, type format short e for scientific notation with 5 decimal places, format longe for scientific notation with 15 significant decimal places and format bank for placingtwo significant digits to the right of the decimal.
The commands who and whos give the names of the variables that have been defined in
the workspace.
The command length(x) returns the length of a vector x and size(x) returns thedimension of the matrix x.
back to list of contents
D. M-files
M-files are macros of MATLAB commands that are stored as ordinary text files with theextension "m", that is filename.m. An M-file can be either a function with input and
output variables or a list of commands. All of the MATLAB examples in this textbookare contained in M-files that are available at the MathWorks ftp site, ftp.mathworks.com
in the directory pub/books/heck.
The following describes the use of M-files on a PC version of MATLAB. MATLAB
requires that the M-file must be stored either in the working directory or in a directory
that is specified in the MATLAB path list. For example, consider using MATLAB on aPC with a user-defined M-file stored in a directory called "\MATLAB\MFILES". Then to
access that M-file, either change the working directory by typing cd\matlab\mfiles from
within the MATLAB command window or by adding the directory to the path.
Permanent addition to the path is accomplished by editing the \MATLAB\matlabrc.m
file, while temporary modification to the path is accomplished by typingpath(path,'\matlab\mfiles') from within MATLAB.
The M-files associated with this textbook should be downloaded from the MathWorks ftp
site and copied to a subdirectory named "\MATLAB\KAMEN" and then this directoryshould be added to the path. The M-files that come with MATLAB are already in
appropriate directories and can be used from any working directory.
66
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
67/88
As example of an M-file that defines a function, create a file in your working directory
named yplusx.m that contains the following commands:
function z = yplusx(y,x)z = y + x;
The following commands typed from within MATLAB demonstrate how this M-file is
used:
x = 2;y = 3;z = yplusx(y,x)
MATLAB M-files are most efficient when written in a way that utilizes matrix or vector
operations. Loops and if statements are available, but should be used sparingly since they
are computationally inefficient. An example of the use of the command foris
for k=1:10,x(k) = cos(k);end
This creates a 1x10 vector x containing the cosine of the positive integers from 1 to 10.
This operation is performed more efficiently with the commands
k = 1:10;x = cos(k);
which utilizes a function of a vector instead of a for loop. An if statement can be used todefine conditional statements. An example is
if(a =4)b = 2;elseb = 3;
end
The allowable comparisons between expressions are >=,
8/8/2019 Simulation Lab 4-06-2010
68/88
Whatever comment is between the quotation marks is displayed to the screen when the
M-file is running, and the user must enter an appropriate value.
2. Fourier Analysis
Commands covered:
dft
idft
fftifft
contfft
Thedft command uses a straightforward method to compute the discrete Fouriertransform. Define a vector x and compute the DFT using the command
X = dft(x)
The first element in X corresponds to the value of X(0).
The command idft uses a straightforward method to compute the inverse discrete Fourier
transform. Define a vector X and compute the IDFT using the command
x = idft(X)
The first element of the resulting vector x is x[0].
For a more efficient but less obvious program, the discrete Fourier transform can be
computed using the command fft which performs a Fast Fourier Transform ofa sequence of numbers. To compute the FFT of a sequence x[n] whichis stored in the vector x, use the command
X = fft(x)
68
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/dft.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/dft.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/idft.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/dft.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/idft.m8/8/2019 Simulation Lab 4-06-2010
69/88
Used in this way, the command fft is interchangeable with the command dft.For more computational efficiency, the length of the vector x should beequal to an exponent of 2, that is 64, 128, 512, 1024, 2048, etc. Thevector x can be padded with zeros to make it have an appropriatelength. MATLAB does this automatically by using the following
command where N is defined to be an exponent of 2:
X = fft(x,N);
The longer the length ofx, the finer the grid will be for the FFT. Due toa wrap around effect, only the first N/2 points of the FFT have anymeaning.
The ifft command computes the inverse Fourier transform:
x = ifft(X);
The FFT can be used to approximate the Fourier transform of acontinuous-time signal as shown in Section 6.6 of the textbook. Acontinuous-time signal x(t) is sampled with a period of T seconds, thenthe DFT is computed for the sampled signal. The resulting amplitudemust be scaled and the corresponding frequency determined. An M-filethat approximates the Fourier Transform of a sampled continuous-timesignal can be downloaded from contfft.m. Let a vector x be defined asthe sampled continuous-time signal x(t) and let T be the samplingtime.
[X,w] = contfft(x,T);
The outputs are the Fourier transform stored in the vector X and thecorresponding frequency vector w.
69
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/contfft.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/contfft.m8/8/2019 Simulation Lab 4-06-2010
70/88
3. Continuous Time System Analysis
Note, the recent versions of Matlab utilize a state space model to represent
a system (where a system sys is defined as sys = ss(A,B,C,D)). Many of the
commands that are listed below have sys as the preferred input argumentrather than num and den. In many cases, the online help for Matlab does
not even indicate the argument list as shown below; however, in most
cases, the argument list as shown below still works. The authors purposely
choose not to present the material in the book or in this tutorial using sys
since it may obscure details for junior and sophomore-level students. For
more details on this notation, see Section 3.F.
A. Transfer Function Representation
Commands covered:
tf2zp
zp2tfcloop
feedback
parallel
series
Transfer functions are defined in MATLAB by storing the coefficients of the numerator
and the denominator in vectors. Given a continuous-time transfer function
where and Store the
coefficients of B(s) and A(s) in the vectors and .In this text, the names of the vectors are generally chosen to be num and den, but any
other name could be used. For example,
is defined by
num = [2 3];
den = [1 4 0 5];
Note that all coefficients must be included in the vector, even zero coefficients.
70
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc377373756http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc3773737568/8/2019 Simulation Lab 4-06-2010
71/88
A transfer function may also be defined in terms of its zeros, poles and gain:
To find the zeros, poles and gain of a transfer function from the vectors num and denwhich contain the coefficients of the numerator and denominator polynomials, type
[z,p,k] = tf2zp(num,den)
The zeros are stored in z, the poles are stored in p, and the gain is stored in k. To find the
numerator and denominator polynomials from z, p, and k, type
[num,den] = zp2tf(z,p,k)
The overall transfer function of individual systems in parallel, series or feedback can be
found using MATLAB. Store the transfer function G in numG and denG, and the transferfunction H in numH and denH.
To reduce the general feedback system to a single transfer function, T(s) = G(s)/
(1+G(s)H(s)) type
[numT,denT] = feedback(numG,denG,numH,denH);
For a unity feedback system, let numH = 1 and denH = 1 before applying theabove algorithm. Alternately, use the command
[numT,denT] = cloop(numG,denG,-1);
To reduce the series system to a single transfer function, T(s) = G(s)H(s) type
[numT,denT] = series(numG,denG,numH,denH);
To reduce the parallel system to a single transfer function, T(s) = G(s) + H(s) type
[numT,denT] = parallel(numG,denG,numH,denH);
(Parallel is not available in the Student Version.)
back to list of contents
B. Time Simulations
Commands covered:
71
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
72/88
residue
step
impulselsim
The analytical method to find the time response of a system requirestaking the inverse Laplace Transform of the output Y(s). MATLAB aidesin this process by computing the partial fraction expansion of Y(s)using the command residue. Store the numerator and denominator coefficients ofY(s) in num and den, then type
[r,p,k] = residue(num,den)
The residues are stored in r, the corresponding poles are stored in p, and the gain is stored
in k. Once the partial fraction expansion is known, an analytical expression for y(t) can
be computed by hand.
A numerical method to find the response of a system to a particular input is available inMATLAB. First store the numerator and denominator of the transfer function in numand den, respectively. To plot the step response, type
step(num,den)
To plot the impulse response, type
impulse(num,den)
For the response to an arbitrary input, use the command lsim. Create avector t which contains the time values in seconds at which you want MATLAB tocalculate the response. Typically, this is done by entering
t = a:b:c;
where a is the starting time, b is the time step and c is the end time. Forsmooth plots, chooseb so that there are at least 300 elements in t (increase asnecessary). Define the input x as a function of time, for example, aramp is defined as x = t. Then plot the response by typing
lsim(num,den,x,t);
To customize the commands, the time vector can be defined explicitlyand the step response can be saved to a vector. Simulating theresponse for five to six time constants generally is sufficient to showthe behavior of the system. For a stable system, a time constant iscalculated as 1/Re(-p) where p is the pole that has the largest real part(i.e., is closest to the origin).
72
8/8/2019 Simulation Lab 4-06-2010
73/88
For example, consider a transfer function defined by
The step response y is calculated and plotted from the followingcommands:
num = 2; den = [1 2];t = 0:3/300:3; % for a time constant of 1/2y = step(num,den,t);plot(t,y)
For the impulse response, simply replace the word step with impulse. Forthe response to an arbitrary input stored in x, type
y = lsim(num,den,x,t);plot(t,y)
back to list of contents
C. Frequency Response Plots
Commands covered:
freqs
bodelogspace
log10semilogxunwrap
To compute the frequency response H of a transfer function, store the numerator and
denominator of the transfer function in the vectors num and den. Define a vector w that
contains the frequencies for which H) is to be computed, for example w = a:b:c where a isthe lowest frequency, c is the highest frequency and b is the increment in frequency. The
command
H = freqs(num,den,w)
returns a complex vector H that contains the value of the frequency response for eachfrequency in w.
To draw a Bode plot of a transfer function which has been stored in the vectors num and
den, type
bode(num,den)
73
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
74/88
To customize the plot, first define the vector w which contains the frequencies at which
the Bode plot will be calculated. Since w should be defined on a log scale, the command
logspace is used. For example, to make a Bode plot ranging in frequencies from 0.1 to100, define w by
w = logspace(-1,2);
The magnitude and phase information for the Bode plot can then be found be executing:
[mag,phase] = bode(num,den,w);
To plot the magnitude in decibels, convert mag using the following command:
magdb = 20*log10(mag);
To plot the results on a semilog scale where the y-axis is linear and the x-axis is
logarithmic, type
semilogx(w,magdb)
for the log-magnitude plot and type
semilogx(w,phase)
for the phase plot. The phase plot may contain jumps of 2 which may not be desired.To remove these jumps, use the command unwrap prior to plotting the phase.
semilogx(w,unwrap(phase))
back to list of contents
D. Analog Filter Design
Commands covered:
buttap
cheb1abzp2tf
lp21plp2bp
lp2hplp2bs
MATLAB contains commands for various analog filter designs, including those for
designing a Butterworth filter and a Type I Chebyshev filter. The commands buttap and
74
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
75/88
cheb1ab are used to design lowpass Butterworth and Type I Chebyshev filters,
respectively, with cutoff frequencies of 1 rad/sec. For an n-pole Butterworth filter, type
[z,p,k] = buttap(n)
where the zeros of the filter are stored in z, the poles are stored in p and the gain of thefilter is in k. For an n-pole Type I Chebyshev filter with Rp decibels of ripple in the
passband, type
[z,p,k] = cheb1ab(n,Rp)
To find the numerator and denominator polynomials of the resulting filter from z, p andk; type
[b,a] = zp2tf(z,p,k)
where a contains the denominator coefficients and b contains the numerator coefficients.Frequency transformations from one lowpass filter to another with a different cutoff
frequency, or from lowpass to highpass, or lowpass to bandstop or lowpass to bandpasscan be performed in MATLAB. These transformations can be used with either the
Butterworth filters or the Chebyshev filters. Suppose b and a store the numerator and
denominator of a transfer function of a lowpass filter with cutoff frequency 1 rad/sec. Tomap to a lowpass filter with cutoff frequency Wo and numerator and denominator
coefficients stored in b1 and a1, type
[b1,a1] = lp2lp(b,a,Wo)
To map to a highpass filter with cutoff frequency Wo, type
[b1,a1] = lp2hp(b,a,Wo)
To map to a bandpass filter with bandwidth Bw centered at the frequency Wo, type
[b1,a1] = lp2bp(b,a,Wo,Bw)
To map to a bandstop filter with stopband bandwidth Bw centered about the frequency
Wo, type
[b1,a1] = lp2bs(b,a,Wo,Bw)
back to list of contents
E. Control Design
Commands covered:
rlocus
75
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
76/88
Consider a feedback loop as shown in Figure 1 where G(s)H(s) = KP(s) and K is a gain
and P(s) contains the poles and zeros of the controller and of the plant. The root locus is a
plot of the roots of the closed loop transfer function as the gain is varied. Suppose that thenumerator and denominator coefficients of P(s) are stored in the vectors num and den.
Then the following command computes and plots the root locus:
rlocus(num,den)
To customize the plot for a specific range of K, say for K ranging from 0 to 100, then usethe following commands:
K = 0:100;
r = rlocus(num,den,K);
plot(r,'.')
The graph contains dots at points in the complex plane that are closed loop poles for
integer values of K ranging from 0 to 100. To get a finer grid of points, use a smallerincrement when defining K, for example, K = 0:.5:100. The resulting matrix r contains
the closed poles for all of the gains defined in the vector K. This is particularly useful tocalculate the closed loop poles for one particular value of K. Note that if the root locus
lies entirely on the real axis, then using plot(r,'.') gives inaccurate results.
back to list of contents
F. State Space Representation
Commands Covered:
ssstep
lsim
ss2tf
tf2ssss2ss
The standard state space representation is used in MATLAB, i.e.,
where x is nx1 vector, u is mx1, y is px1, A is nxn, B is nxm, and C is pxn. The response
of a system to various inputs can be found using the same commands that are used for
transfer function representations: step, impulse, and lsim. The argument list contains theA, B, C, and D matrices instead of the numerator and denominator vectors. Alternately,
the system can be combined into one model using the command
76
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
77/88
sys = ss(A,B,C,D);
Then, sys can be used as an input argument for the other commands. For example, the
step response is obtained by typing either of the following commands:
[y,t,x] = step(A,B,C,D);[y,t,x] = step(sys);
The states are stored in x, the outputs in y and the time vector, which is automatically
generated, is stored in t. The rows of x and y contain the states and outputs for the time
points in t. Each column of x represents a state. For example, to plot the second stateversus time, type
plot(t,x(:,2))
To find the response of an arbitrary input or to find the response to initial conditions, use
lsim. Define a time vector t and an input matrix u with the same number of rows as in tand the number of columns equaling the number of inputs. An optional argument is the
initial condition vector x0. The command is then given as
[y,x] = lsim(A,B,C,D,u,t,x0) or [y,x] = lsim(sys,u,t,x0)
You can find the transfer function for a single-input/single-output (SISO) system using
the command:
[num,den] = ss2tf(A,B,C,D);
The numerator coefficients are stored in num and the denominator coefficients are storedin den.
Given a transformation matrix P, the ss2ss function will perform the similarity transform.
Store the state space model in A, B, C and D and the transformation matrix in P.
[Abar,Bbar,Cbar,Dbar]=ss2ss(A,B,C,D,P) or [Abar,Bbar,Cbar,Dbar] = ss2ss(sys,P)
performs the similarity transform z=Px resulting in a state space system that is defined as:
where .
77
8/8/2019 Simulation Lab 4-06-2010
78/88
4. Discrete-Time System Analysis
A. Convolution
Commands covered:
conv
deconv
To perform discrete time convolution, x[n]*h[n], define the vectors x and h with elements
in the sequences x[n] and h[n]. Then use the command
y = conv(x,h)
This command assumes that the first element in x and the first element in h correspond ton=0, so that the first element in the resulting output vector corresponds to n=0. If this is
not the case, then the output vector will be computed correctly, but the index will have to
be adjusted. For example,
x = [1 1 1 1 1];h = [0 1 2 3];
y = conv(x,h);
yields y = [0 1 3 6 6 6 5 3]. If x is indexed as described above, then y[0] = 0, y[1] = 1, ....
In general, total up the index of the first element in h and the index of the first element in
x, this is the index of the first element in y. For example, if the first element in hcorresponds to n = -2 and the first element in x corresponds to n = -3, then the first
element in y corresponds to n = -5.
Care must be taken when computing the convolution of infinite duration signals. If thevector x has length q and the vector h has length r, then you musttruncate the vector y to have length min(q,r). See the comments inProblem 3.7 of the textbook for additional information.
The command conv can also be used to multiply polynomials: suppose that thecoefficients of a(s) are given in the vector a and the coefficients of b(s) are given in thevector b, then the coefficients of the polynomial a(s)b(s) can be found as the elements of
the vector defined by ab = conv(a,b).
The command deconv is the inverse procedure to the convolution. In this text, it is used
as a means of dividing polynomials. Given a(s) and b(s) with coefficients stored in a and
78
8/8/2019 Simulation Lab 4-06-2010
79/88
b, then the coefficients of c(s) = b(s)/a(s) are found by using the command c =
deconv(b,a).
back to list of contents
B. Transfer Function Representation
For a discrete-time transfer function, the coefficients are stored in descending powers of z
or ascending powers of . For example,
then define the vectors as
num = [2 3 4];den = [1 5 6];
back to list of contents
C. Time Simulations
Commands Covered:
recur
convdstep
dimpulsefilter
There are three methods to compute the response of a system described by the followingrecursive relationship
The first method uses the command recur and is useful when there are nonzero initial
conditions. This command is available from the MathWorks ftp site and a shortened
version is given in Figure C.5 of the textbook. The inputs to the function are the
coefficients stored in the vectors and , the initial
conditions on x and on y are stored in the vectors x0 = [x[n0-M], x[n0-M+1],...,x[n0-1]]
and y0 = [y[n0-N], y[n0-N+1],...,y[n0-1]]], and the time indices for which the solution
79
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
80/88
needs to be calculated are stored in the vector n where n0 represents the first element in
this vector. To use recur, type
y = recur(a,b,n,x,x0,y0);
The output is a vector y with elements y[n]; the first element of y corresponds to thetime index n0. For example, consider the system described by
y[n] - 0.6y[n-1] + 0.08y[n-2] = x[n-1]
where x[n] = u[n] and with initial conditions y[-1] = 2, y[-2] = 1, andx[-1] = x[-2] = 0. To compute the response y[n] for n = 0, 1,...,10, type
a = [-0.6 0.08]; b = [0 1];x0 = 0; y0 = [1 2];n = 0:10;
x = ones(1,11);y = recur(a,b,n,x,x0,y0);
The vector y contains the values of y[n] for n = 0,1,...,10.
The second method to compute the response uses convolution and isuseful when the initial conditions on y are zero. This method involvesfirst finding the impulse response of the system, h[n], and thenconvolving h[n] with x[n] as discussed in Section 4.A. For example,consider the system described above with zero initial conditions, thatis, y[-1]=y[-2]=0. The impulse response for this system is
. The commands to compute y[n] are
n = 0:10;x = ones(1,11);h = 5*(0.4).^n - 5*(.02).^n;y = conv(x,h);y = y(1:length(n));
The vector y contains the values of y[n] for n = 0,1,...,10. Note that thevector was truncated to length(n) because both x[n] and h[n] are infiniteduration signals. See the comments in Section 4.A regarding theconvolution of infinite duration signals.
The third method of solving for the response requires that the transferfunction of the system be known. The commands dstep and dimpulsecompute the unit step response and the unit impulse response, respectively while the
command filter computes the response to initial conditions and to arbitrary inputs. The
denominator coefficients are stored as and the numerator coefficients
80
8/8/2019 Simulation Lab 4-06-2010
81/88
are stored as where there are N-M zeros padded on theend of the coefficients. For example, consider the system given abovewith initial conditions y[-1] = y[-2] = 0. To compute the step responsefor n=0 to n=10, type the commands
n = 0:10;num = [0 1 0]; den = [1 -0.6 0.08];y = dstep(num,den,length(n));
The response can then be plotted using the stem plot. To compute the impulse response,simply replace dstep with dimpulse in the above commands.
To compute the response to an arbitrary input, store the input sequence in the vector x.
The command
y = filter(num,den,x);
is used to compute the system response. If the system has nonzero initial conditions, theinitial conditions can be stored in a vector v0. For a first order system where N=M=1,
define . For a second order system where N=M=2, define
. To compute the response withnonzero initial conditions, type
y = filter(num,den,x,zi);
For example, consider the previous system with the initial conditions y[-1] = 2 and y[-2]
= 1 and input x[n] = u[n]. Type the following commands to compute y[n].
n = 0:10; x = ones(1:11);num = [0 1 0]; den = [1 -0.6 0.08];
zi = [0.6*2-0.08*1, -0.08*2];
y = filter(num,den,x,zi);
back to list of contents
D. Frequency Response Plots
Commands covered:
freqz
The DTFT of a system can be calculated from the transfer function using freqz. Definethe numerator and the denominator of the transfer function in num and den. The
command
[H,Omega] = freqz(num,den,n,'whole');
81
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
82/88
computes the DTFT for n points equally spaced around the unit circle at the frequencies
contained in the vector Omega. The magnitude of H is found from abs(H) and the phase
of H is found from angle(H). To customize the range for , define a vector Omega of
desired frequencies, for example Omega = -pi:2*pi/300:pi defines a vector of length 301
with values that range from - to . To get the DTFT at these frequencies, type
H = freqz(num,den,Omega);
back to list of contents
E. Digital Filter Design
Commands covered:
bilinearbutter
cheby1hamminghanning
The analog prototype method of designing IIR filters can be done by first designing an
analog filter with the desired characteristics as shown in Section 3.D, then mapping the
filter to the discrete-time domain. Store the numerator and denominator of the analogfilter, H(s), in the vectors num and den, and let T be the sampling period. Then the
numerator and denominator of the digital filter H(z) is found from the following
command
[numd,dend] = bilinear(num,den,1/T)
Alternately, the commands butter and cheby1 automatically design the analog filter and
then use the bilinear transformation to map the filter to the discrete-time domain.
Lowpass, highpass, bandstop, and bandpass filters can be designed using this method.
The digital cutoff frequencies must be specified; these should be normalized by . Todesign a digital lowpass filter based on the analog Butterworth filter, use the commands:
[num,den] = butter(n,Omegac)
where n is the number of poles and Omegac is the normalized digital cutoff frequency,
. To design a highpass filter with cutoff frequency Omegac, use thecommands
[num,den] = butter(n,Omegac,'high')
To design a bandpass filter with passband from Omega1 to Omega2, define Omega =
[Omega1,Omega2] and use the command
82
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor1450518/8/2019 Simulation Lab 4-06-2010
83/88
[num,den] = butter(n,Omega)
To design a bandstop filter with stopband from Omega1 to Omega2, define Omega =
[Omega1, Omega2] and use the command
[num,den] = butter(n,Omega,'stop')
The design for an nth order Type I Chebyshev filter is accomplished using the samemethods as for butter except that "butter" is replaced by "cheby1":
[num,den] = cheby1(n,Omegac); % for a lowpass filter
[num,den] = cheby1(n,Omegac,'high'); % for a highpass filter
If Omega has two elements,
[num,den] = cheby1(n,Omega); % for a bandpass
[num,den] = cheby1(n,Omega,'stop'); % for a bandstop
The windows used in FIR filter design are given by
w = boxcar(N) % rectangular window
w = hamming(N)w = hanning(N)
These commands are used to truncate the infinite impulse response of an ideal digital
filter with the result being an FIR filter with length N.
The Signal Processing Toolbox also provides commands for computing the FIR filterdirectly. To obtain an FIR filter with length N and cutoff frequency Omegac (normalized
by ) use the command
h = fir1(N-1,Omegac)
The vector h contains the impulse response of the FIR where h(1) is the value of h[0].
A length N highpass filter with normalized cutoff frequency Omegac is designed byusing the command
h = fir1(N-1,Omegac,'high')
A bandpass with passband from Omega1 to Omega2 is obtained by typing
h = fir1(N-1,Omega)
where Omega = [Omega1,Omega2]. A bandstop filter with stopband from Omega1 toOmega2 is obtained by typing
83
8/8/2019 Simulation Lab 4-06-2010
84/88
h = fir1(N-1,Omega,'stop')
where Omega = [Omega1,Omega2]. The fir1 command uses the Hamming window by
default. Other windows are obtained by adding an option of 'hanning' or 'boxcar' to thearguments; for example,
h = fir1(N-1,Omegac,'high',boxcar(N))
creates a highpass FIR filter with cutoff frequency Omegac using a rectangular window.
back to list of contents
F. Digital Control Design
Commands covered:
bilinearc2dmhybrid
An analog controller G(s) can be mapped to a digital controller D(z) using the bilinear
transformation or the step response matching method. Store the numerator anddenominator of G(s) in num and den. Then the numerator and denominator of D(z) is
found from the bilinear transformation using the commands
[numd,dend] = bilinear(num,den,1/T)
where T is the sampling frequency. To use the step invariant method, use the commands
[numd,dend] = c2dm(num,den,T,'zoh')
To simulate the response of a continuous-time plant G(s) with a digital controller D(z),use the command hybrid. Consider the block diagram in Figure 11.25 of the text. The
numerator and denominator coefficients of the plant are stored in numG and denG; the
numerator and denominator coefficients of the controller are stored in numD and denD;the reference input signal is stored in r; and the sampling time is stored in T. The
increments in the time vector should selected to be the sampling time divided by aninteger, for example, t = 0:b:Tend where there is some integer m such that bm=T. Thecommand is used as
[y,ud] = hybrid(numG,denG,numD,denD,T,t,r);
The outputs of the command are the system response, y, and the control signal that is
input to the plant, ud. The M-file contains a loop which computes the discrete-time
84
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/hybrid.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/hybrid.mhttp://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tutorial.html#anchor145051http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/hybrid.m8/8/2019 Simulation Lab 4-06-2010
85/88
control and then simulates the continuous-time plant for T seconds with the constant
control. The process repeats for the next T second interval.
G. State Space Representation
Commands Covered:
dlsimdstep
dimpulse
Most of the commands for the continuous time state space representation also work for
the discrete time state space. For example, ss2tf, tf2ss, and ss2ss for discrete time areused exactly the same way as for the continuous time case discussed inSection 3.F.
There is a discrete time version of the command lsim, which is used as follows:
[y,x] = dlsim(A,B,C,D,u,n);
where the output is stored in y, the states are stored in x, the input is stored in u and the
time index is stored in n.
5. Plotting
Commands covered:
plot
xlabel
ylabeltitle
gridaxis
stem
subplot
85
http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc377373756http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc377373756http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc377373756http://users.ece.gatech.edu/~bonnie/book/TUTORIAL/tut_3.html#_Toc3773737568/8/2019 Simulation Lab 4-06-2010
86/88
The command most often used for plotting is plot, which creates linear plots of vectors
and matrices; plot(t,y) plots the vector t on the x-axis versus vector y on the y-axis. There
are options on the line type and the color of the plot which are obtained usingplot(t,y,'option'). The linetype options are '-' solid line (default), '--' dashed line, '-.' dot
dash line, ':' dotted line. The points in y can be left unconnected and delineated by a
variety of symbols: + . * o x. The following colors are available options:
r red
b blue
g green
w white
k black
For example, plot(t,y,'--') uses a dashed line, plot(t,y,'*') uses * at all the points defined in
t and y without connecting the points, and plot(t,y,'g') uses a solid green line. The options
can also be used together, for example, plot(t,y,'g:') plots a dotted green line.
To plot two or more graphs on the same set of axes, use the command plot(t1,y1,t2,y2),
which plots y1 versus t1 and y2 versus t2.
To label your axes and give the plot a title, type
xlabel('time (sec)')ylabel('step response')
title('My Plot')
Finally, add a grid to your plot to make it easier to read. Type
grid
The problem that you will encounter most often when plotting functions is thatMATLAB will scale the axes in a way that is different than you want them to appear.
You can easily override the autoscaling of the axes by using the axis command after the
plotting command:
axis([xmin xmax ymin ymax]);
where xmin, xmax, ymin, and ymax are numbers corresponding to the limits you desirefor the axes. To return to the automatic scaling, simply type axis.
For discrete-time signals, use the command stem which plots each point with a small
open circle and a straight line. To plot y[k] versus k, type stem(k,y). To obtain filledcircles, as the plots appear in the textbook, use the command stem(k,y,'filled').
86
8/8/2019 Simulation Lab 4-06-2010
87/88
To plot more than one graph on the screen, use the command subplot(mnp) which
partitions the screen into an mxn grid where p determines the position of the particular
graph counting the upper left corner as p=1. For example,
subplot(211),semilogx(w,magdb);
subplot(212),semilogx(w,phase);
plots the bode plot with the log-magnitude plot on top and the phase plot below. Titles
and labels can be inserted immediately after the appropriate semilogx command or plotcommand. To return to a full screen plot, type subplot(111).
6. Loading and Saving Data
When using MATLAB, you may wish to leave the program but save the vectors andmatrices you have defined. To save the file to the working directory, type
save filename
where "filename" is a name of your choice. To retrieve the data later, type
load filename
87
8/8/2019 Simulation Lab 4-06-2010
88/88