




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















MATLAB Tutorial
This tutorial is available as a supplement to the textbook Fundamentals of Signals and Systems Using Matlab by Edward Kamen and Bonnie Heck, published by Prentice Hall. The tutorial covers basic MATLAB commands that are used in introductory signals and systems analysis. It is meant to serve as a quick way to learn MATLAB and a quick reference to the commands that are used in this textbook. For more detailed information, the reader should consult the official MATLAB documentation. An easy way to learn MATLAB is to sit down at a computer and follow along with the examples given in this tutorial and the examples given in the textbook.
The tutorial is designed for students using either the professional version of MATLAB (ver. 5.0) with the Control Systems Toolbox (ver. 4.0) and the Signal Processing Toolbox (ver. 4.0), or using the Student Edition of MATLAB (ver. 5.0). The commands covered in the tutorial and their descriptions are also valid for MATLAB version 4.0.
The topics covered in this tutorial are:
1. MATLAB Basics 2 A. Definition of Variables 2 B. Definition of Matrices 4 C. General Information 6 **D. M-files 6
1. MATLAB Basics
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+
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:
A variable can be assigned using a formula that utilizes these operators and either numbers 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 the end of the line) and continue on the next line.
c = 1+2+3+... 5+6+7;
c = exp(y) yields: c = -1.0751 + 7.3104i
which can be verified by using Euler's formula:
c = e^2 cos(8) + je^2 sin(8)
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 vector v = [1 3 5 7 8]. Previously defined vectors can be used to define a new vector. For example, with v defined above
a = [9 10]; b = [v a];
creates the vector b = [1 3 5 7 8 9 10].
The second method is used for creating vectors with equally spaced elements:
t = 0:.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]; 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 vector x that contains the elements of x(t) = tcos(t) at specific points in time, you cannot simply multiply the vector t with the vector cos(t). Instead you multiply their elements together:
t = 0:10; x = t.*cos(t);
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 for is
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 to define conditional statements. An example is
if(a <= 2), b = 1; elseif(a >=4) b = 2; else b = 3; end
The allowable comparisons between expressions are >=, <=, <, >, ==, and ~=.
Several of the M-files written for this textbook employ a user-defined variable which is defined with the command input. For example, suppose that you want to run an M-file with different values of a variable T. The following command line within the M-file defines the value:
T = input('Input the value of T: ')
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 fft ifft contfft
The dft command uses a straightforward method to compute the discrete Fourier transform. 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 function dft is available from the MathWorks ftp site and is defined in Figure C.2 of the textbook.
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]. The function idft is available at the MathWorks ftp site and is defined in Figure C.3 of the textbook.
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 of a sequence of numbers. To compute the FFT of a sequence x[n] which is stored in the vector x, use the command
X = fft(x)
Used in this way, the command fft is interchangeable with the command dft. For more computational efficiency, the length of the vector x should be equal to an exponent of 2, that is 64, 128, 512, 1024, 2048, etc. The vector x can be padded with zeros to make it have an appropriate length. 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 of x, the finer the grid will be for the FFT. Due to a wrap around effect, only the first N/2 points of the FFT have any meaning.
The ifft command computes the inverse Fourier transform:
x = ifft(X);
3. Continuous Time System Analysis
A. Transfer Function Representation
Commands covered: tf2zp zp2tf cloop 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
H(s) =
B(s) A(s)
where B(s) = bMsM+bM-1sM-1+...+b 0 and A(s) = sN+aN-1sN-1+...+a 0. Store the coefficients of B(s) and A(s) in the vectors num = [bM bM-1 ... b 0 ] and den = [1 aN-1 ... a 0 ]. 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,
H(s) =
2s+ 3 s + 4s^3 2 + 5
is defined by
num = [2 3]; den = [1 4 0 5];
Note that all coefficients must be included in the vector, even zero coefficients.
A transfer function may also be defined in terms of its zeros, poles and gain:
H(s) = k(s- z )(s- z ) (s- z ) (s- p )(s- p ) (s- p )
1 2 m 1 2 n
To find the zeros, poles and gain of a transfer function from the vectors num and den which 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
unity feedback
feedback
[num,den] = zp2tf(z,p,k)
The overall transfer function of individual systems in parallel, series or feedback can be found using MATLAB. Consider block diagram reduction of the different configurations shown in Figure 1. Store the transfer function G in numG and denG, and the transfer function H in numH and denH.
To reduce the general feedback system to a single transfer function, Gcl(s) = G(s)/(1+G(s)H(s)) type
[numcl,dencl] = feedback(numG,denG,numH,denH);
For a unity feedback system, let numH = 1 and denH = 1 before applying the above algorithm. Alternately, use the command
[numcl,dencl] = cloop(numG,denG,-1);
To reduce the series system to a single transfer function, Gs(s) = G(s)H(s) type
[nums,dens] = series(numG,denG,numH,denH);
To reduce the parallel system to a single transfer function, Gp(s) = G(s) + H(s) type
[nump,denp] = parallel(numG,denG,numH,denH);
(Parallel is not available in the Student Version.)
To plot the impulse response, type
impulse(num,den)
For the response to an arbitrary input, use the command lsim. Create a vector t which contains the time values in seconds at which you want MATLAB to calculate 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. For smooth plots, choose b so that there are at least 300 elements in t (increase as necessary). Define the input x as a function of time, for example, a ramp 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 explicitly and the step response can be saved to a vector. Simulating the response for five to six time constants generally is sufficient to show the behavior of the system. For a stable system, a time constant is calculated as 1/Re(-p) where p is the pole that has the largest real part (i.e., is closest to the origin).
For example, consider a transfer function defined by
H(s) =
s+ 2
The step response y is calculated and plotted from the following commands:
num = 2; den = [1 2]; t = 0:3/300:3; % for a time constant of 1/ y = step(num,den,t); plot(t,y)
For the impulse response, simply replace the word step with impulse. For the response to an arbitrary input stored in x, type
y = lsim(num,den,x,t); plot(t,y)
C. Frequency Response Plots
Commands covered: freqs bode logspace log semilogx unwrap
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 is the 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 H(ω) for each frequency 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)
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 10-1^ to 10^2 , 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)
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)
E. Control Design
Commands covered: rlocus
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 the numerator 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 use the 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 smaller increment 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 to calculate 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.
F. State Space Representation
Commands Covered: step lsim ss2tf tf2ss ss2ss
The standard state space representation is used in MATLAB, i.e.,
x^ & Ax Bu y Cx
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 the A, B, C, and D matrices instead of the numerator and denominator vectors. For example, the step response is obtained by typing:
[y,x,t] = step(A,B,C,D);
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 state versus 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 t and 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);
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 stored in 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);
performs the similarity transform z=Px resulting in a state space system that is defined as:
x & Ax Bu y Cx Du
where A = PAP-1, B = PB, C = CP-1, D = D.
then define the vectors as
num = [2 3 4]; den = [1 5 6];
C. Time Simulations
Commands Covered: recur conv dstep dimpulse filter
There are three methods to compute the response of a system described by the following recursive 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. of the textbook. The inputs to the function are the coefficients ai and bi stored in the vectors a = [a 1 a 2 ... aN] and b = [b 0 b 1 ... bM], the initial conditions on x and on y are stored in the vectors x0 = [x[n 0 -M], x[n 0 -M+1],...,x[n 0 -1]] and y0 = [y[n 0 -N], y[n 0 - N+1],...,y[n 0 -1]]], and the time indices for which the solution needs to be calculated are stored in the vector n where n 0 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 the time index n 0. 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, and x[-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.
y[n] + [ ] [ ] i=
N
i=
M
The second method to compute the response uses convolution and is useful when the initial conditions on y are zero. This method involves first finding the impulse response of the system, h[n], and then convolving h[n] with x[n] as discussed in Section 4.A. For example, consider the system described above with zero initial conditions, that is, y[-1]=y[-2]=0. The impulse response for this system is h[n] = 5[(0.4)n-(0.2)n]u[n]. 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 the vector was truncated to length(n) because both x[n] and h[n] are infinite duration signals. See the comments in Section 4.A regarding the convolution of infinite duration signals.
The third method of solving for the response requires that the transfer function of the system be known. The commands dstep and dimpulse compute 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 den = [1 a 1 a 2 ... aN] and the numerator coefficients are stored as num = [b 0 b 1 ... bM, 0 ... 0] where there are N-M zeros padded on the end of the coefficients. For example, consider the system given above with initial conditions y[-1] = y[-2] = 0. To compute the step response for 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, the initial conditions can be stored in a vector v0. For a first order system where N=M=1, define zi = [b 1 x[-1]-ay[-1]]. For a second order system where N=M=2, define zi = [b 1 *x[- 1]+b 2 *x[-2]-a 1 *y[-1]-a 2 *y[-2], b 1 *x[-1]-a 2 *y[-1]]. To compute the response with nonzero 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].