Vous êtes sur la page 1sur 134

MATLAB Control System Tutorial

Chapter 1: Matlab Basic Tutorial..1 Chapter 2: Matlab Modeling Tutorial...9 Chapter 3: PDI Tutorial...13 Chapter 4: Root Locus Tutorial...24 Chapter 5: Frequency Response Analysis and Design....39 Chapter 6: Designing Lead and Lag Compensators....61 Appendix.70

MATLAB Basics Tutorial


Vectors Functions Plotting Polynomials Matrices Printing Using M-files in MATLAB Getting help in MATLAB Key MATLAB Commands used in this tutorial are: plot polyval roots conv deconv inv eig poly MATLAB is an interactive program for numerical computation and data visualization; it is used extensively by control engineers for analysis and design. There are many different toolboxes available which extend the basic functions of MATLAB into different application areas; in these tutorials, we will make extensive use of the Control Systems Toolbox. MATLAB is supported on Unix, Macintosh, and Windows environments; a student version of MATLAB is available for personal computers. For more information on MATLAB, contact the MathWorks. The idea behind these tutorials is that you can view them in one window while running MATLAB in another window. You should be able to re-do all of the plots and calculations in the tutorials by cutting and pasting text from the tutorials into MATLAB or an m-file.

Vectors
Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between brackets, and set it equal to a variable. For example, to create the vector a, enter into the M ATLAB command window (you can "copy" and "paste" from your browser into M ATLAB to make it easy):
a = [1 2 3 4 5 6 9 8 7]

MATLAB should return:


a = 1 2 3 4 5 6 9 8 7

Let's say you want to create a vector with elements between 0 and 20 evenly spaced in increments of 2 (this method is frequently used to create a time vector):
t = 0:2:20 t = 0 2 4 6 8 10 12 14 16 18 20

Manipulating vectors is almost as easy as creating them. First, suppose you would like to add 2 to each of the elements in vector 'a'. The equation for that looks like:
b = a + 2 b = 3 4 5 6 7 8 11 10 9

Now suppose, you would like to add two vectors together. If the two vectors are the same length, it is easy. Simply add the two as shown below:
c = a + b c = 4 6 8 10 12 14 20 18 16

Subtraction of vectors of the same length works exactly the same way.

Functions
To make life easier, MATLAB includes many standard functions. Each function is a block of code that accomplishes a specific task. M ATLAB contains all of the standard functions such as sin, cos, log, exp, sqrt, as well as many others. Commonly used constants such as pi, and i or j for the square root of -1, are also incorporated into MATLAB.
sin(pi/4) ans = 0.7071

To determine the usage of any function, type help MATLAB command window.

[function name]

at the

MATLAB even allows you to write your own functions with the function command; follow the link to learn how to write your own functions and see a listing of the functions we created for this tutorial.

Plotting
It is also easy to create plots in MATLAB. Suppose you wanted to plot a sine wave as a function of time. First make a time vector (the semicolon after each statement tells MATLAB we don't want to see all the values) and then compute the sin value at each time.
t=0:0.25:7; y = sin(t); plot(t,y)

The plot contains approximately one period of a sine wave. Basic plotting is very easy in MATLAB, and the plot command has extensive add-on capabilities. You may get more information about plotting in MATLAB in the appendix.

Polynomials
In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:

To enter this into MATLAB, just enter it as a vector in the following manner
x = [1 3 -15 -2 9] x = 1 3 -15 -2 9

MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,

would be represented in MATLAB as:


y = [1 0 0 0 1]

You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,
z = polyval([1 0 0 0 1],2) z = 17

You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as

Finding the roots would be as easy as entering the following command;


roots([1 3 -15 -2 9]) ans = -5.5745 2.5836 -0.7951 0.7860

Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. M ATLAB's function conv that will do this for you.
x = [1 2]; y = [1 4 8]; z = conv(x,y) z = 1 6 16 16

Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.
[xx, R] = deconv(z,y) xx = 1 R = 0 0 0 0 2

As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero.

Matrices
Entering matrices into MATLAB is the same as entering a vector, except each row of elements is separated by a semicolon (;) or a return:
B = [1 2 3 4;5 6 7 8; B = 1 5 9 B = [ 1 5 B = 1 5 9 2 6 10 3 7 11 4 8 12 2 6 3 7 2 6 10 4 8 9 10 11 12 ] 3 7 11 4 8 12 9 10 11 12 ]

Matrices in MATLAB can be manipulated in many ways. For one, you can find the transpose of a matrix using the apostrophe key:
C = B' C = 1 2 3 4 5 6 7 8 9 10 11 12

It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the matrix is not complex). Now you can multiply the two matrices B and C together. Remember that order matters when multiplying matrices.
D = B * C D = 30 70 110 D = C * B D = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224 70 174 278 110 278 446

Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this).
E = [1 2;3 4] F = [2 3;4 5] G = E .* F E = 1 3 F = 2 4 G = 2 12 6 20 3 5 2 4

If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power.
E^3 ans = 37 81 54 118

If wanted to cube each element in the matrix, just use the element-by-element cubing.
E.^3 ans = 1 27 8 64

You can also find the inverse of a matrix:


X = inv(E) X = -2.0000 1.5000 1.0000 -0.5000

or its eigenvalues:
eig(E) ans = -0.3723 5.3723

There is even a function to find the coefficients of the characteristic polynomial of a matrix. The "poly" function creates a vector that includes the coefficients of the characteristic polynomial.
p = poly(E) p = 1.0000 -5.0000 -2.0000

Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial:
roots(p) ans = 5.3723 -0.3723

Printing
Printing in MATLAB is pretty easy. Just follow the steps illustrated below: Macintosh To print a plot or a m-file from a Macintosh, just click on the plot or mfile, select Print under the File menu, and hit return. Windows To print a plot or a m-file from a computer running Windows, just select Print from the File menu in the window of the plot or m-file, and hit return. Unix To print a plot on a Unix workstation enter the command:
print -P<printername>

If you want to save the plot and print it later, enter the command:
print plot.ps

Sometime later, you could print the plot using the command "lpr P plot.ps" If you are using a HP workstation to print, you would instead use the command "lpr -d plot.ps" To print a m-file, just print it the way you would any other file, using the command "lpr -P <name of m-file>.m" If you are using a HP workstation to print, you would instead use the command "lpr d plot.ps<name of m-file>.m"

Using M-files in MATLAB


There are slightly different things you need to know for each platform. Macintosh There is a built-in editor for m-files; choose "New M-file" from the File menu. You can also use any other editor you like (but be sure to save the files in text format and load them when you start M ATLAB). Windows Running MATLAB from Windows is very similar to running it on a Macintosh. However, you need to know that your m-file will be saved in the clipboard. Therefore, you must make sure that it is saved as filename.m Unix You will need to run an editor separately from MATLAB. The best strategy is to make a directory for all your m-files, then cd to that directory before running both MATLAB and the editor. To start MATLAB from your Xterm window, simply type: matlab. You can either type commands directly into MATLAB, or put all of the commands that you will need together in an m-file, and just run the file. If you put all of your m-files in the same directory that you run MATLAB from, then MATLAB will always find them. For more information on M-files go to the appendix.

Getting help in MATLAB


MATLAB has a fairly good on-line help; type help commandname for more information on any given command. You do need to know the name of the command that you are looking for; a list of the all the ones used in these tutorials is given in the command listing; a link to this page can be found at the bottom of every tutorial and example page.

Here are a few notes to end this tutorial. You can get the value of a particular variable at any time by typing its name.
B B = 1 4 7 2 5 8 3 6 9

You can also have more that one statement on a single line, so long as you separate them with either a semicolon or comma. Also, you may have noticed that so long as you don't assign a variable a specific operation or result, MATLAB with store it in a temporary variable called "ans".

MATLAB Modeling Tutorial


Train system Free body diagram and Newton's law State-variable and output equations MATLAB representation MATLAB can be used to represent a physical system or a model. In this tutorial, you will learn how to enter a differential equation model into M ATLAB. Let's start with a review of how to represent a physical system as a set of differential equations.

Train system
In this example, we will consider a toy train consisting of an engine and a car. Assuming that the train only travels in one direction, we want to apply control to the train so that it has a smooth start-up and stop, along with a constantspeed ride. The mass of the engine and the car will be represented by M1 and M2, respectively. The two are held together by a spring, which has the stiffness coefficient of k. F represents the force applied by the engine, and the Greek letter, mu (which will also be represented by the letter ), represents the coefficient of rolling friction.

Free body diagram and Newton's law


The system can be represented by following Free Body Diagrams.

From Newton's law, you know that the sum of forces acting on a mass equals the mass times its acceleration. In this case, the forces acting on M1 are the spring, the friction and the force applied by the engine. The forces acting on M2 are the spring and the friction. In the vertical direction, the gravitational force is canceled by the normal force applied by the ground, so that there will be no acceleration in the vertical direction. The equations of motion in the horizontal direction are the following:

State-variable and output equations


This set of system equations can now be manipulated into state-variable form. The state variab are the positions, X1 and X2, and the velocities, V1 and V2; the input is F. The state variable equations will look like the following:

Let the output of the system be the velocity of the engine. Then the output equation will be:

1. Transfer function
To find the transfer function of the system, we first take the Laplace transforms of the differential equations.

The output is Y(s) = V2(s) = s X2(s). The variable X1 should be algebraically eliminated to leave an expression for Y(s)/F(s). When finding the transfer function, zero initial conditions must be assumed. The transfer function should look like the one shown below.

2. State-space
Another method to solve the problem is to use the state-space form. Four matrices A, B, C, and D characterize the system behavior, and will be used to solve the problem. The state-space form which is found from the statevariable and the output equations is shown below.

MATLAB representation
Now we will show you how to enter the equations derived above into an mfile for MATLAB. Since MATLAB can not manipulate symbolic variables, let's assign numerical values to each of the variables:

M1 = 1 kg M2 = 0.5 kg k = 1 N/m F= 1 N u = 0.002 sec/m g = 9.8 m/s^2

Create an new m-file and enter the following commands.


M1=1; M2=0.5; k=1; F=1; u=0.002; g=9.8;

Now you have one of two choices: 1) Use the transfer function, or 2) Use the state-space form to solve the problem. If you choose to use the transfer function, add the following commands onto the end of the m-file which you have just created.
num=[M2 M2*u*g 1]; den=[M1*M2 2*M1*M2*u*g M1*k+M1*M2*u*u*g*g+M2*k M1*k*u*g+M2*k*u*g]; train=tf(num,den)

If you choose to use the state-space form, add the following commands at the end of the m-file, instead of num and den matrices shown above.
A=[ 0 1 0 0; -k/M1 -u*g k/M1 0; 0 0 0 1; k/M2 0 -k/M2 -u*g]; B=[ 0; 1/M1; 0; 0]; C=[0 1 0 0]; D=[0]; train=ss(A,B,C,D)

Continue solving the problem


Once the differential equation representing the system model has been entered into MATLAB in either transfer-function or state-space form, the open loop and closed loop system behavior can be studied. Most operations can be done using either the transfer function or the statespace model. Furthermore, it is simple to transfer between the two if the other form of representation is required. If you need to learn how to convert from one representation to the other, see the Conversions chapter in the appendix. You can see seven examples more of MATLAB modeling in the Examples Tutorials

PID Tutorial
Introduction The three-term controller The characteristics of P, I, and D controllers Example Problem Open-loop step response Proportional control Proportional-Derivative control Proportional-Integral control Proportional-Integral-Derivative control General tips for designing a PID controller Key MATLAB Commands used in this tutorial are: step feedback

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

Plant: A system to be controlled Controller: Provides the excitation for the plant; Designed to control the overall system behavior

The three-term controller


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

= Proportional gain = Integral gain = Derivative gain

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

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

The characteristics of P, I, and D controllers


A proportional controller ( ) will have the effect of reducing the rise time and will reduce but never eliminate the steady-state error. An integral control ( ) will have the effect of eliminating the steady-state error, but it may make the transient response worse. A derivative control ( ) will have the effect of increasing the stability of the system, reducing the overshoot, and improving the transient response. Effects of each of controllers , , and on a closed-loop system are summarized in the table shown below.
CL RESPONSE RISE TIME OVERSHOOT SETTLING TIME S-S ERROR Decrease Decrease Small Change Increase Increase Decrease Small Change Increase Decrease Decrease Eliminate Small Change

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

Example Problem
Suppose we have a simple mass, spring, and damper problem.

The modeling equation of this system is

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

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

Let

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

Plug these values into the above transfer function

The goal of this problem is to show you how each of contributes to obtain

and

Fast rise time Minimum overshoot No steady-state error

Open-loop step response


Let's first view the open-loop step response. Create a new m-file and add in the following code:
num=1; den=[1 10 20]; plant=tf(num,den); step(plant)

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

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

Proportional control
From the table shown above, we see that the proportional controller ( ) reduces the rise time, increases the overshoot, and reduces the steady-state error. The closed-loop transfer function of the above system with a proportional controller is:

Let the proportional gain ( following:

) equal 300 and change the m-file to the

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

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

Note: The MATLAB function called feedback was used to obtain a closed-loop transfer function directly from the open-loop transfer function (instead of computing closed-loop transfer function by hand). The above plot shows that the proportional controller reduced both the rise time and the steady-state error, increased the overshoot, and decreased the settling time by small amount.

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

Let equal 300 as before and let equal 10. Enter the following commands into an m-file and run it in the MATLAB command window.
Kp=300; Kd=10; contr=tf([Kd Kp],1); sys_cl=feedback(contr*plant,1); t=0:0.01:2; step(sys_cl,t)

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

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

Let's reduce the Kp to 30, and let Ki equal 70. Create an new m-file and enter the following commands.
Kp=30; Ki=70; contr=tf([Kp Ki],[1 0]); sys_cl=feedback(contr*plant,1); t=0:0.01:2; step(sys_cl,t)

Run this m-file in the MATLAB command window, and you should get the following plot.

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

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

After several trial and error runs, the gains =350, =300, and =50 provided the desired response. To confirm, enter the following commands to an m-file and run it in the command window. You should get the following step response.
Kp=350; Ki=300; Kd=50; contr=tf([Kd Kp Ki],[1 0]); sys_cl=feedback(contr*plant,1); t=0:0.01:2; step(sys_cl,t)

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

General tips for designing a PID controller


When you are designing a PID controller for a given system, follow the steps shown below to obtain a desired response.
1. Obtain an open-loop response and determine what needs to be

2. 3. 4. 5.

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

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

Root Locus Tutorial


Closed-Loop poles Plotting the root locus of a transfer function Choosing a value of K from root locus Closed-loop response Example: Root Locus Design Method for DC Motor Position Control Drawing the open-loop root locus Model reduction Integral Control Proportional plus Integral Control Proportional plus Integral plus Derivative Control Finding the gain using the rlocfind command and plotting the closedloop response Key MATLAB commands used in this tutorial: feedback, rlocfind, rlocus, sgrid,
step

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

The closed-loop transfer function is:

and thus the poles of the closed loop system are values of s such that 1 + K H(s) = 0. If we write H(s) = b(s)/a(s), then this equation has the form:

Let n = order of a(s) and m = order of b(s) [the order of a polynomial is the highest power of s that appears in it]. We will consider all positive values of k. In the limit as , the poles of the closed-loop system are a(s) = 0 or the poles of H(s). In the limit as the poles of the closed-loop system are b(s) = 0 or the zeros of H(s). ,

No matter what we pick k to be, the closed-loop system must always have n poles, where n is the number of poles of H(s). The root locus must have n branches, each branch starts at a pole of H(s) and goes to a zero of H(s). If H(s) has more poles than zeros (as is often the case), m < n and we say that H(s) has zeros at infinity. In this case, the limit of H(s) as , is zero. The number of zeros at infinity is n-m, the number of poles minus the number of zeros, and is the number of branches of the root locus that go to infinity (asymptotes). Since the root locus is actually the locations of all possible closed loop poles, from the root locus we can select a gain such that our closed-loop system will perform the way we want. If any of the selected poles are on the right half plane, the closed-loop system will be unstable. The poles that are closest to the imaginary axis have the greatest influence on the closed-loop response, so even though the system has three or four poles, it may still act like a second or even first order system depending on the location(s) of the dominant pole(s).

Plotting the root locus of a transfer function


Consider an open loop system which has a transfer function of

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

Choosing a value of K from the root locus


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

On the plot above, the two dotted lines at about a 45 degree angle indicate pole locations with Zeta = 0.7; in between these lines, the poles will have Zeta > 0.7 and outside of the lines Zeta < 0.7. The semicircle indicates pole locations with a natural frequency Wn = 1.8; inside the circle, Wn < 1.8 and outside the circle Wn > 1.8. Going back to our problem, to make the overshoot less than 5%, the poles have to be in between the two white dotted lines, and to make the rise time shorter than 1 second, the poles have to be outside of the white dotted semicircle. So now we know only the part of the locus outside of the semicircle and in between the two lines are acceptable. All the poles in this location are in the left-half plane, so the closed-loop system will be stable. From the plot above we see that there is part of the root locus inside the desired region. So in this case we need only a proportional controller to move the poles to the desired region. You can use rlocfind command in MATLAB to choose the desired poles on the locus:
[k,poles] = rlocfind(sys)

Click on the plot the point where you want the closed-loop pole to be. You may want to select the points indicated in the plot below to satisfy the design criteria.

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

Closed-loop response
In order to find the step response, you need to know the closed-loop transfer function. You could compute this using the rules of block diagrams, or let MATLAB do it for you:
sys_cl= feedback(k*sys,1)

The two arguments to the function feedback are the numerator and denominator of the open-loop system. You need to include the proportional gain that you have chosen. Unity feedback is assumed. If you have a non-unity feedback situation, look at the help file for the MATLAB function feedback, which can find the closed-loop transfer function with a gain in the feedback loop. Check out the step response of your closed-loop system:
step(sys_cl)

As we expected, this response has an overshoot less than 5% and a rise time less than 1 second.

Example: Root Locus Design Method for DC Motor Position Control


Consider de following DC motor position controller set up. The motor is modeled us a circuit, and the lead as a disc of intercia J.

From the diagram above, we may derive the following ecuations:

and the system schematic looks like:

With a 1 rad/sec step reference, the design criteria are:


Settling time less than 0.04 seconds Overshoot less than 16% No steady-state error to a reference No steady-state error due to a disturbance

Now let's design a controller using the root locus method.

Create a new m-file and type in the following commands (refer to main problem for the details of getting those commands).
J=3.2284E-6; b=3.5077E-6; K=0.0274; R=4; L=2.75E-6; num=K; den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0]; motor=tf(num,den);

Drawing the open-loop root locus


The main idea of root locus design is to find the closed-loop response from the open-loop root locus plot. Then by adding zeros and/or poles to the original plant, the closed-loop response will be modified. Let's first view the root locus for the plant. Add the following commands at the end of your m-file.
rlocus(motor) sgrid(.5,0) sigrid(100)

The commands sgrid and sigrid are functions. Sgrid is a function in the control systems tool box, but sigrid is not. You need to copy the sigrid.m file to your directory. The variab in the sgrid command are the zeta term (0.5 corresponds to a overshoot of 16%), and the wn term (no rise time criteria) respectively. The variable in the sigrid command is the sigma term ( ). Run the above m-file and you should get the root locus plot below:

If you look at the axis scales on this plot, one open-loop pole is very far to the left (further than -1x ). This pole does not affect the closed loop dynamics unless very large gains are used, where the system becomes unstable. We will ignore this pole by doing a model reduction.

Model Reduction
If you have a transfer function which has one (or more) poles to the far left of the dominant poles, you can neglect these poles and the closed-loop response for small gains will not be affected (for large gains, these poles will push the root locus to the right-half plane, causing instability). The correct way to neglect these poles, keeping the DC gain of the transfer function constant, is as follows:

Let's see what the poles of the original transfer function are. Enter the following command at the MATLAB prompt:
roots(den)

You should see the following output:


ans = 1.0e+06 * 0 -1.4545 -0.0001

We want to neglect the pole at -1.45e6. This can be translated into MATLAB code as:
J=3.2284E-6; b=3.5077E-6; K=0.0274; R=4; L=2.75E-6; num=K; den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0]; poles=roots(den); den2=deconv(den,[1/max(abs(poles)) 1]); motor=tf(num,den2);

You can now check that the other poles have not been affected by entering
roots(den2)

at the MATLAB prompt. Now we can draw the root locus of the reduced system. Add the following commands to the end of your m-file and re-run it.
rlocus(motor) sgrid(.5,0) sigrid(100)

You should obtain the following plot in which you can see that the closedloop system will be stable for small gains.

We can see from this plot that the closed-loop poles are never fast enough to meet the settling time requirement (that is, they never move to the left of the sigma=100 vertical line). Also, recall that we need an integrator in the controller (not just in the system) to remove steady-state error due to a disturbance.

Integral Control
Now, let's try using integral control to remove steady-state error to a disturbance. Modify your m-file so it looks like:
J=3.2284E-6; b=3.5077E-6; K=0.0274; R=4; L=2.75E-6; num=K; den=[(J*L) ((J*R)+(L*b)) ((b*R)+K^2) 0]; poles=roots(den); den2=deconv(den,[1/max(abs(poles)) 1]); motor=tf(num,den2);

contr=tf(1,[1 0]); rlocus(contr*motor) sgrid(.5,0) sigrid(100)

Note that this adds a 1/s term to the forward loop. Run this m-file and you will obtain the following plot.

From this root locus we can see that the closed-loop system under integral control is never stable, and another controller must be used.

Proportional plus Integral Control


Now, let's modify the integral controller to a PI controller. Using PI instead of I control adds a zero to the open-loop system. We'll place this zero at s=-20. The zero must lie between the open-loop poles of the system in this case so that the closed-loop will be stable. Change the lines defining the controller (numcf and dencf) in your m-file to the following.
contr=tf([1 20],[1 0]);

Re-run your m-file and obtain the following plot.

Note: You may not get a similar plot in your MATLAB window, depending on which version of the rlocus command you are using. If the MATLAB output does not satisfy the rules of the root locus, or does not match your expectations, you can always specify which gains you would like MATLAB to plot. For this particular root locus, the following commands (replacing the rlocus command above) work well.
gain = 0:0.1:20; rlocus(contr*motor,gain)

Now, we have managed to stabilize the system with zero steady-state error to a disturbance, but the system will still not be fast enough.

Proportional plus Integral plus Derivative Control


In order to pull the root locus further to the left, to make it faster, we need to place a second open-loop zero, resulting in a PID controller. After some experimentation, we can place the two PID zeros at and . Change the lines defining the controller in your m-file to the following.
numc=conv([1 60],[1 70]); denc=[1 0]; contr=tf(numc,denc);

Re-run your m-file and obtain the following plot.

Now, we can see that two of the closed-loop poles loop around well within both the settling time and percent overshoot requirements. The third closed loop pole moves from the open-loop pole at s=-59.2 to the open loop zero at s=-60. This closed-loop pole nearly cancels with the zero (which remains in the closed loop transfer function) because it is so close. Therefore, we can ignore its effect. However, the other open-loop zero also remains in the closed-loop, and will affect the response, slowing it down, and adding overshoot. Therefore, we have to be conservative in picking where on the root locus we want the closed-loop poles to lie.

Finding the gain using the rlocfind command


If you recall, we need the settling time and the overshoot to be as small as possible, particularly because of the effect of the extra zero. Large damping corresponds to points on the root locus near the real axis. A fast response corresponds to points on the root locus far to the left of the imaginary axis. To find the gain corresponding to a point on the root locus, we can use the rlocfind command. We can find the gain and plot the step response using this gain all at once. To do this, enter the following commands at the end of your m-file and rerun it.
[k,poles] = rlocfind(contr*motor) sys_cl=feedback(k*contr*motor,1); t=0:0.001:.1; step(sys_cl,t)

Go to the plot and select a point on the root locus on left side of the loop, close to the real axis as shown below with the small + marks. This will ensure that the response will be as fast as possible with as little overshoot as possible.

These pole locations would indicate that the response would have almost no overshoot, but you must remember that the zero will add some overshoot.

After doing this, you should see the following output in the M ATLAB command window.
selected_point = -1.3943e+02+ k = 0.1309 poles = 1.0e+06 * -1.4542 -0.0001 + 0.0000i -0.0001 - 0.0000i -0.0001 1.8502e+01i

Note that the values returned in your MATLAB command window may not be exactly the same, but should at least have the same order of magnitude. You should also get the following step response plot:

As you can see, the system has an overshoot of approximately 15%, a settling time of approximately 0.04 seconds, and no steady-state error. Let's now look at the disturbance response by computing the closed-loop disturbance transfer function and plotting its step response. Add the following lines to your m-file:
dist_cl=feedback(motor,k*contr); step(dist_cl,t)

Re-run your m-file, selecting the same point on the root locus, and you will get the following plot.

You can see that the response to a step disturbance reaches a steady-state value of zero, and in fact, stays within 0.02 (or 2%) after 0.04 seconds. Therefore, all the design requirements have been met. In this example, we placed zeros on the root locus to shape it the way we wanted. While some trial-and error is necessary to place the zeros, it is helpful to understand how the root locus is drawn, and MATLAB is used to verify and refine the placement.

Frequency Response Analysis and Design


I. Bode plots Gain and phase margin | Bandwidth frequency | Closed loop response II. The Nyquist diagram Closed loop stability | Gain margin | Phase margin

Key MATLAB commands used in these tutorial are bode, nyquist, nyquist1, lnyquist, margin, lsim, step, and feedback The frequency response method may be less intuitive than other methods you have studied previously. However, it has certain advantages, especially in real-life situations such as modeling transfer functions from physical data. The frequency response of a system can be viewed two different ways: via the Bode plot or via the Nyquist diagram. Both methods display the same information; the difference lies in the way the information is presented. We will study both methods in this tutorial. The frequency response is a representation of the system's response to sinusoidal inputs at varying frequencies. The output of a linear system to a sinusoidal input is a sinusoid of the same frequency but with a different magnitude and phase. The frequency response is defined as the magnitude and phase differences between the input and output sinusoids. In this tutorial, we will see how we can use the open-loop frequency response of a system to predict its behavior in closed-loop. To plot the frequency response, we create a vector of frequencies (varying between zero or "DC" and infinity) and compute the value of the plant transfer function at those frequencies. If is the open loop transfer function of a system and w is the frequency vector, we then plot vs. w. Since is a complex number, we can plot both its magnitude and phase (the Bode plot) or its position in the complex plane (the Nyquist plot). More information is available on plotting the frequency response.

Bode Plots
As noted above, a Bode plot is the representation of the magnitude and phase of , where the frequency vector contains only positive frequencies. To see the Bode plot of a transfer function, you can use the M ATLAB bode command. For example,
num = 50; den = [1 9 30 40]; sys = tf(num,den) bode(sys)

displays the Bode plots for the transfer function:


50 ----------------------s^3 + 9 s^2 + 30 s + 40

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

To see a few simple Bode plots, go to the appendix.

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

where is a variable (constant) gain and is the plant under consideration. The gain margin is defined as the change in open loop gain required to make the system unstable. Systems with greater gain margins can withstand greater changes in system parameters before becoming unstable in closed loop. Keep in mind that unity gain in magnitude is equal to a gain of zero in dB. The phase margin is defined as the change in open loop phase shift required to make a closed loop system unstable. The phase margin also measures the system's tolerance to time delay. If there is a time delay greater than in the loop, where is the frequency where the phase shift is 180 deg, the system will become unstable in closed loop. The time delay can be thought of as an extra block in the forward path of the block diagram that adds phase to the system but has no effect the gain. That is, a time delay can be represented as a block with magnitude of 1 and phase (in radians/second). For now, we won't worry about where all this comes from and will concentrate on identifying the gain and phase margins on a Bode plot. The phase margin is the difference in phase between the phase curve and -180 deg at the point corresponding to the frequency that gives us a gain of 0dB (the gain cross over frequency, ). Likewise, the gain margin is the difference between the magnitude curve and 0dB at the point corresponding to the frequency that gives us a phase of -180 deg (the phase cross over frequency, ).

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

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

As you can see the phase plot is exactly the same as before, and the magnitude plot is shifted up by 40dB (gain of 100). The phase margin is now about -60 degrees. This same result could be achieved if the y-axis of the magnitude plot was shifted down 40dB. Try this, look at the first Bode plot, find where the curve crosses the -40dB line, and read off the phase margin. It should be about -60 degrees, the same as the second Bode plot. We can find the gain and phase margins for a system directly, by using MATLAB. Just use the margin command. This command returns the gain and phase margins, the gain and phase cross over frequencies, and a graphical representation of these on the Bode plot. Let's check it out:
margin(sys)

Bandwidth Frequency The bandwidth frequency is defined as the frequency at which the closedloop magnitude response is equal to -3 dB. However, when we design via frequency response, we are interested in predicting the closed-loop behavior from the open-loop response. Therefore, we will use a second-order system approximation and say that the bandwidth frequency equals the frequency at which the open-loop magnitude response is between -6 and - 7.5dB, assuming the open loop phase response is between -135 deg and -225 deg. For a complete derivation of this approximation, consult your textbook.
If you would like to see how the bandwidth of a system can be found mathematically from the closed-loop damping ratio and natural frequency, the relevant equations as well as some plots and MATLAB code are given on the appendix Bandwidth Frequency . In order to illustrate the importance of the bandwidth frequency, we will show how the output changes with different input frequencies. We will find that sinusoidal inputs with frequency less than (the bandwidth frequency) are tracked "reasonably well" by the system. Sinusoidal inputs with frequency greater than are attenuated (in magnitude) by a factor of 0.707 or greater (and are also shifted in phase). Let's say that we have the following closed-loop transfer function representing a system:
1 --------------s^2 + 0.5 s + 1

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

Since this is the closed-loop transfer function, our bandwidth frequency will be the frequency corresponding to a gain of -3 dB. Looking at the plot, we find that it is approximately 1.4 rad/s. We can also read off the plot that for an input frequency of 0.3 radians, the output sinusoid should have a magnitude about one and the phase should be shifted by perhaps a few degrees (behind the input). For an input frequency of 3 rad/sec, the output magnitude should be about -20dB (or 1/10 as large as the input) and the phase should be nearly 180 (almost exactly out-of-phase). We can use the lsim command to simulate the response of the system to sinusoidal inputs. First, consider a sinusoidal input with a frequency lower than . We must also keep in mind that we want to view the steady state response. Therefore, we will modify the axes in order to see the steady state response clearly (ignoring the transient response).
w = 0.3; num = 1; den = [1 0.5 1]; sys = tf(num,den); t = 0:0.1:100; u = sin(w*t); [y,t] = lsim(sys,u,t); plot(t,y,t,u) axis([50,100,-2,2])

Note that the output (blue) tracks the input (purple) fairly well; it is perhaps a few degrees behind the input as expected. However, if we set the frequency of the input higher than the bandwidth frequency for the system, we get a very distorted response (with respect to the input):
w = 3; num = 1; den = [1 0.5 1]; sys = tf(num,den); t = 0:0.1:100; u = sin(w*t); [y,t] = lsim(sys,u,t); plot(t,y,t,u) axis([90, 100, -1, 1])

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

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

The system must be stable in open loop if we are going to design via Bode plots. If the gain cross over frequency is less than the phase cross over frequency (i.e. ), then the closed-loop system will be stable. For second-order systems, the closed-loop damping ratio is approximately equal to the phase margin divided by 100 if the phase margin is between 0 and 60 deg. We can use this concept with caution if the phase margin is greater than 60 deg. For second-order systems, a relationship between damping ratio, bandwidth frequency and settling time is given by an equation described on the appendix bandwidth frequency. A very rough estimate that you can use is that the bandwidth is approximately equal to the natural frequency.

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

Where Gc(s) is the controller and G(s) is:


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

The design must meet the following specifications:


Zero steady state error. Maximum overshoot must be less than 40%. Settling time must be less than 2 secs.

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

There are several characteristics of the system that can be read directly from this Bode plot. First of all, we can see that the bandwidth frequency is around 10 rad/sec. Since the bandwidth frequency is roughly the same as the natural frequency (for a first order system of this type), the rise time is 1.8/BW=1.8/10=1.8 seconds. This is a rough estimate, so we will say the rise time is about 2 seconds. The phase margin for this system is approximately 95 degrees. The relation only holds for . Since the system is first-order, there should be no overshoot. The last major point of interest is steady-state error. The steady-state error can be read directly off the Bode plot as well. The constant (Kp, Kv, or Ka) is found from the intersection of the low frequency asymptote with the line. Just extend the low frequency line to the line. The magnitude at

this point is the constant. Since the Bode plot of this system is a horizontal line at low frequencies (slope = 0), we know this system is of type zero. Therefore, the intersection is easy to find. The gain is 20dB (magnitude 10). What this means is that the constant for the error function is 10. The steadystate error is . If our system was type one instead of type zero, the constant for the steady-state error would be found in a manner similar to the following

Let's check our predictions by looking at a step response plot. This can be done by adding the following two lines of code into the MATLAB command window.
sys_cl = feedback(sys,1); step(sys_cl)

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

K*(s+a) Gc(s) = ------s

The first thing we need to find is the damping ratio corresponding to a percent overshoot of 40%. Plugging in this value into the equation relating overshoot and damping ratio (or consulting a plot of this relation), we find that the damping ratio corresponding to this overshoot is approximately 0.28. Therefore, our phase margin should be at least 30 degrees. From our plot, we find that . We must have a bandwidth frequency greater than or equal to 12 if we want our settling time to be less than 1.75 seconds which meets the design specs. Now that we know our desired phase margin and bandwidth frequency, we can start our design. Remember that we are looking at the open-loop Bode plots. Therefore, our bandwidth frequency will be the frequency corresponding to a gain of approximately -7 dB. Let's see how the integrator portion of the PI or affects our response. Change your m-file to look like the following (this adds an integral term but no proportional term):
num = 10; den = [1.25 1]; plant = tf(num,den); numPI = 1; denPI = [1 0]; contr = tf(numPI,denPI); bode(contr * plant, logspace(0,2))

Our phase margin and bandwidth frequency are too small. We will add gain and phase with a zero. Let's place the zero at 1 for now and see what happens. Change your m-file to look like the following:
num = 10; den = [1.25 1]; plant = tf(num,den); numPI = [1 1]; denPI = [1 0]; contr = tf(numPI,denPI); bode(contr * plant, logspace(0,2))

It turns out that the zero at 1 with a unit gain gives us a satisfactory answer. Our phase margin is greater than 60 degrees (even less overshoot than expected) and our bandwidth frequency is approximately 11 rad/s, which will give us a satisfactory response. Although satisfactory, the response is not quite

as good as we would like. Therefore, let's try to get a higher bandwidth frequency without changing the phase margin too much. Let's try to increase the gain to 5 and see what happens. This will make the gain shift and the phase will remain the same.
num = 10; den = [1.25 1]; plant = tf(num,den); numPI = 5*[1 1]; denPI = [1 0]; contr = tf(numPI,denPI); bode(contr * plant, logspace(0,2))

That looks really good. Let's look at our step response and verify our results. Add the following two lines to your m-file:
sys_cl = feedback(contr * plant,1); step(sys_cl)

As you can see, our response is better than we had hoped for. However, we are not always quite as lucky and usually have to play around with the gain and the position of the poles and/or zeros in order to achieve our design requirements.

The Nyquist Diagram


The Nyquist plot allows us to predict the stability and performance of a closed-loop system by observing its open-loop behavior. The Nyquist criterion can be used for design purposes regardless of open-loop stability (remember that the Bode design methods assume that the system is stable in open loop). Therefore, we use this criterion to determine closed-loop stability when the Bode plots display confusing information. By following this link (http://www. engin.umich.edu/class/ctms/freq/movie3.htm) youll have access to a movie that will help you visualize the relationship between the Bode plot and the Nyquist diagram.

Note: The MATLAB nyquist command does not provide an adequate representation for systems that have open-loop poles in the jw-axis. Therefore, we suggest that you copy the nyquist1.m file as a new m-file. This m-file creates more accurate Nyquist plots, since it correctly deals with poles and zeros on the jw-axis.

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

In order to see how the frequency vector contributes to the Nyquist diagram more clearly, you can view our movie. However, if we have open-loop poles or zeros on the axis, will not be defined at those points, and we must loop around them when we are plotting the contour. Such a contour would look as follows:

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

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

as in the

If encircles the origin, then will enclose the point -1. Since we are interested in the closed-loop stability, we want to know if there are any closed-loop poles (zeros of ) in the right-half plane. More details on how to determine this will come later. Therefore, the behavior of the Nyquist diagram around the -1 point in the real axis is very important; however, the axis on the standard nyquist diagram might make it hard to see what's happening around this point. To correct this, you can add the lnyquist.m function to your files. The lnyquist.m command plots the Nyquist diagram using a logarithmic scale and preserves the characteristics of the -1 point.

To view a simple Nyquist plot using MATLAB, we will define the following transfer function and view the Nyquist plot:
0.5 ------s - 0.5 sys=tf(0.5,[1 -0.5]); nyquist(sys)

Now we will look at the Nyquist diagram for the following transfer function:
s + 2 ----s^2

Note that this function has a pole at the origin. We will see the difference between using the nyquist, nyquist1, and lnyquist commands with this particular function.
num = [1 2]; den = [1 0 0]; sys = tf(num,den); nyquist(sys)

nyquist1(sys)

lnyquist(sys)

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

Closed Loop Stability


Consider the negative feedback system:

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

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

The Nyquist criterion then states that:


P = the number of open-loop (unstable) poles of G(s)H(s) N = the number of times the Nyquist diagram encircles -1 clockwise encirclements of -1 count as positive encirclements counter-clockwise (or anti-clockwise) encirclements of -1 count as negative encirclements

Z = the number of right half-plane (positive, real) poles of the closedloop system

The important equation which relates these three quantities is:

Note: This is only one convention for the Nyquist criterion. Another convention states that a positive N counts the counter-clockwise or anticlockwise encirclements of -1. The P and Z variab remain the same. In this case the equation becomes Z = P - N. Throughout these tutorials, we will use a positive sign for clockwise encirclements. It is very important (and somewhat tricky) to learn how to count the number of times that the diagram encircles -1. Therefore, we will go into some detail to help you visualize this. You can view this movie as an example. Another way of looking at it is to imagine you are standing on top of the -1 point and are following the diagram from beginning to end. Now ask yourself: How many times did I turn my head a full 360 degrees? Again, if the motion was clockwise, N is positive, and if the motion is anti-clockwise, N is negative. Knowing the number of right-half plane (unstable) poles in open loop (P), and the number of encirclements of -1 made by the Nyquist diagram (N), we can determine the closed-loop stability of the system. If Z = P + N is a positive, nonzero number, the closed-loop system is unstable. We can also use the Nyquist diagram to find the range of gains for a closedloop unity feedback system to be stable. The system we will test looks like this:

where

is :
s^2 + 10 s + 24 --------------s^2 - 8 s + 15

This system has a gain K which can be varied in order to modify the response of the closed-loop system. However, we will see that we can only vary this gain within certain limits, since we have to make sure that our closed-loop system will be stable. This is what we will be looking for: the range of gains that will make this system stable in the closed loop. The first thing we need to do is find the number of positive real poles in our open-loop transfer function:
roots([1 -8 15]) ans = 5 3

The poles of the open-loop transfer function are both positive. Therefore, we need two anti-clockwise (N = -2) encirclements of the Nyquist diagram in order to have a stable closed-loop system (Z = P + N). If the number of encirclements is less than two or the encirclements are not anti-clockwise, our system will be unstable. Let's look at our Nyquist diagram for a gain of 1:
sys = tf([ 1 10 24], [ 1 -8 15]); nyquist(sys)

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

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

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

K = 0.79
sys=tf([1 10 24], [1 -8 15]); w=logspace(-2,3,501); k=0.79; nyquist(k*sys,w);

Note that the Nyquist diagram does not loop around the -1 point. We will now look at our step response. Remember that we must look at the closed-loop step response.
sys_cl = feedback(k*sys,1); step(sys_cl)

The system is unstable.

K = 0.80
k=0.80; nyquist(k*sys,w);

Note that the Nyquist diagram goes right through the -1 point. We will now look at our step response. Remember that we must look at the closed-loop step response.
sys_cl = feedback(k*sys,1); step(sys_cl)

The system is marginally stable.

K = 0.81
k=0.81; nyquist(k*sys,w)

Note that the Nyquist diagram encircles the -1 point. We will now look at our step response. Remember that we must look at the closed-loop step response.
sys_cl = feedback(k*sys,1); step(sys_cl)

The system is stable.

Gain Margin We already defined the gain margin as the change in open-loop gain expressed in decibels (dB), required at 180 degrees of phase shift to make the system unstable. Now we are going to find out where this comes from. First of all, let's say that we have a system that is stable if there are no Nyquist encirclements of -1, such as:
50 ----------------------s^3 + 9 s^2 + 30 s + 40

Looking at the roots, we find that we have no open loop poles in the right half plane and therefore no closed-loop poles in the right half plane if there are no Nyquist encirclements of -1. Now, how much can we vary the gain before this system becomes unstable in closed loop? Let's look at the following figure:

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

Therefore, we say that the gain margin is units. However, we mentioned before that the gain margin is usually measured in decibels. Hence, the gain margin is :
GM = 20*log10(a) [dB]

We will now find the gain margin of the stable, open-loop transfer function we viewed before. Recall that the function is:
50 ----------------------s^3 + 9 s^2 + 30 s + 40

and that the Nyquist diagram can be viewed by typing:


sys = tf(50, [1 9 30 40 ]); nyquist(sys)

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

which means

(this is the rightmost point in the Nyquist diagram) or at this point using polyval:

. We can then find the value of

w=sqrt(30); polyval(50,j*w)/polyval([1 9 30 40],j*w)

You should get the following output from MATLAB


ans = -0.2174

The answer is: . The imaginary part is zero, so we know that our answer is correct. We can also verify by looking at the Nyquist plot again. The real part also makes sense. Now we can proceed to find the gain margin. We found that the 180 degrees phase shift occurs at . This point was previously defined as . Therefore, we now have , which is the gain margin. However, we need to express the gain margin in decibels,
-1/a = -0.2174 => a = 4.6 => GM = 20*log10( 4.6) = 13.26 dB

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

The plot appears to go right through the -1 point. We can verify the accuracy of our results by viewing the zoomed Nyquist diagrams and step responses for gains of 4.5, 4.6, and 4.7. The results obtain will be the same that those obtain varying the value of K between 0.81 and 0.79.

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

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

Designing Lead and Lag Compensators


Lead compensator using root locus Lead compensator using frequency response Lag compensator using root locus Lag compensator using frequency response Lead-lag compensators Lead and lag compensators are used quite extensively in control. A lead compensator can increase the stability or speed of response of a system; a lag compensator can reduce (but not eliminate) the steady state error. Depending on the effect desired, one or more lead and lag compensators may be used in various combinations. Lead, lag, and lead/lag compensators are usually designed for a system in transfer function form. The conversions page in the appendix explains how to convert a state-space model into transfer function form.

Lead or phase-lead compensator using root locus


A first-order lead compensator can be designed using the root locus. A lead compensator in root locus form is given by

where the magnitude of is less than the magnitude of . A phase-lead compensator tends to shift the root locus toward the left half plane. This results in an improvement in the system's stability and an increase in the response speed. How is this accomplished? If you recall finding the asymptotes of the root locus that lead to the zeros at infinity, the equation to determine the intersection of the asymptotes along the real axis is:

stand for the number of poles, and

for the number of zeros.

When a lead compensator is added to a system, the value of this intersection will be a larger negative number than it was before. The net number of zeros and poles will be the same (one zero and one pole are added), but the added pole is a larger negative number than the added zero. Thus, the result of a lead compensator is that the asymptotes' intersection is moved further into the left half plane, and the entire root locus will be shifted to the left. This can increase the region of stability as well as the response speed. In MATLAB a phase lead compensator in root locus form is implemented by using the transfer function in the form
numlead = kc*[1 z]; denlead = [1 p]; lead = tf(numlead,denlead);

and we can interconnect it with a plant as follows:


sys = lead*plant;

Lead or phase-lead compensator using frequency response


A first-order phase-lead compensator can be designed using the frequency response. A lead compensator in frequency response form is given by

Note that this is equivalent to the root locus form

with

, and

. In frequency response design, the

phase-lead compensator adds positive phase to the system over the frequency range following to . A bode plot of a phase-lead compensator looks like the

The two corner frequencies are at 1/aT and 1/T; note the positive phase that is added to the system between these two frequencies. Depending on the value of a, the maximum added phase can be up to 90 degrees; if you need more than 90 degrees of phase, two lead compensators can be used. The maximum amount of phase is added at the center frequency, which is located at

The equation which determines the maximum phase is

Additional positive phase increases the phase margin and thus increases the stability of the system. This type of compensator is designed by determining from the amount of phase needed to satisfy the phase margin requirements, and determining to place the added phase at the new gaincrossover frequency. Another effect of the lead compensator can be seen in the magnitude plot. The lead compensator increases the gain of the system at high frequencies (the amount of this gain is equal to a). This can increase the crossover frequency, which will help to decrease the rise time and settling time of the system. In MATLAB, a phase lead compensator in frequency response form is implemented by using the transfer function in the form
numlead = kc*[1 z]; denlead = [1 p]; lead = tf(numlead,denlead);

and we can interconnect it with a plant as follows:


sys = lead*plant;

Lag or Phase-Lag Compensator using Root Locus


A first-order lag compensator can be designed using the root locus. A lag compensator in root locus form is given by

where the magnitude of zo is greater than the magnitude of po. A phase-lag compensator tends to shift the root locus to the right, which is undesirable. For this reason, the pole and zero of a lag compensator must be placed close together (usually near the origin) so they do not appreciably change the transient response or stability characteristics of the system. How does the lag controller shift the root locus to the right? If you recall finding the asymptotes of the root locus that lead to the zeros at infinity, the equation to determine the intersection of the asymptotes along the real axis is:

When a lag compensator is added to a system, the value of this intersection will be a smaller negative number than it was before. The net number of zeros and poles will be the same (one zero and one pole are added), but the added pole is a smaller negative number than the added zero. Thus, the result of a lag compensator is that the asymptotes' intersection is moved closer to the right half plane, and the entire root locus will be shifted to the right. It was previously stated that that lag controller should only minimally change the transient response because of its negative effect. If the phase-lag compensator is not supposed to change the transient response noticeably, what is it good for? The answer is that a phase-lag compensator can improve the system's steady-state response. It works in the following manner. At high frequencies, the lag controller will have unity gain. At low frequencies, the gain will be which is greater than 1. This factor will multiply the position, velocity, or acceleration constant ( , , or ), and the steadystate error will thus decrease by the factor . In MATLAB, a phase lead compensator in root locus form is implemented by using the transfer function in the form

numlag = [1 z]; denlag = [1 p]; lag = tf(numlag,denlag);

and we can interconnect it with a plant as follows:


sys = lag*plant;

Lag or Phase-Lag Compensator using Frequency Response


A first-order phase-lag compensator can be designed using the frequency response. A lag compensator in frequency response form is given by

The phase-lag compensator looks similar to a phase-lead compensator, except that a is now less than 1. The main difference is that the lag compensator adds negative phase to the system over the specified frequency range, while a lead compensator adds positive phase over the specified frequency. A bode plot of a phase-lag compensator looks like the following

The two corner frequencies are at 1/T and 1/aT. The main effect of the lag compensator is shown in the magnitude plot. The lag compensator adds gain at low frequencies; the magnitude of this gain is equal to a. The effect of this gain is to cause the steady-state error of the closed-loop system to be decreased by a factor of a. Because the gain of the lag compensator is unity at middle and high frequencies, the transient response and stability are not impacted too much.

The side effect of the lag compensator is the negative phase that is added to the system between the two corner frequencies. Depending on the value a, up to -90 degrees of phase can be added. Care must be taken that the phase margin of the system with lag compensation is still satisfactory. In MATLAB, a phase-lag compensator in frequency response form is implemented by using the transfer function in the form
numlag = [a*T 1]; denlag = a*[T 1]; lag = tf(numlag,denlag);

and we can interconnect it with a plant as follows:


sys = lag*plant;

Lead-lag Compensator using either Root Locus or Frequency Response


A lead-lag compensator combines the effects of a lead compensator with those of a lag compensator. The result is a system with improved transient response, stability and steady-state error. To implement a lead-lag compensator, first design the lead compensator to achieve the desired transient response and stability, and then add on a lag compensator to improve the steady-state response.

Appendix
Index: Matlab command list. Introduction to Matlab functions. Introduction to M-files. Plotting in Matlab. Step response in Matlab. Steady state error. Pole Zero cancellation. Plotting frequency response. Sample Bode plots. Bandwidth frequency. Function sigrid. Function Inyquist. Function nyquist1. Convertions between system representations

MATLAB Commands List


The following list of commands can be very useful for future reference. Use "help" in MATLAB for more information on how to use the commands. In these tutorials, we use commands both from MATLAB and from the Control Systems Toolbox, as well as some commands/functions which we wrote ourselves. For those commands/functions which are not standard in M ATLAB, we give links to their descriptions. For more information on writing MATLAB functions, see the function page. Note: MATLAB commands from the control system toolbox are highlighted in red. Non-standard MATLAB commands are highlighted in green.
Command abs acker axis bode c2d clf conv ctrb deconv det dlqr eig eps feedback Absolute value Compute the K matrix to place the poles of A-BK, see also place Set the scale of the current plot, see also plot, figure Draw the Bode plot, see also logspace, margin, nyquist1 Continuous system to discrete system Clear figure Convolution (useful for multiplying polynomials), see also deconv The controllability matrix, see also obsv Deconvolution and polynomial division, see also conv Find the determinant of a matrix Linear-quadratic regulator design for discrete-time systems, see also lqr Compute the eigenvalues of a matrix MATLAB's numerical tolerance Connect linear systems in a feedback loop Description

figure for format function grid gtext help hold if imag impulse input inv legend length linspace lnyquist log loglog logspace lqr lsim margin minreal

Create a new figure or redefine the current figure, see also subplot, axis For, next loop Number format (significant digits, exponents) Creates function m-files Draw the grid lines on the current plot Add a piece of text to the current plot, see also text HELP! Hold the current graph, see also figure Conditionally execute statements Returns the imaginary part of a complex number, see also real Impulse response of linear systems, see also step, lsim Prompt for user input Find the inverse of a matrix Graph legend Length of a vector, see also size Returns a linearly spaced vector Produce a Nyquist plot on a logarithmic scale, see also nyquist1 natural logarithm, also log10: common logarithm Plot using log-log scale, also semilogx/semilogy Returns a logarithmically spaced vector Linear quadratic regulator design for continuous systems, see also dlqr Simulate a linear system, see also step, impulse Returns the gain margin, phase margin, and crossover frequencies, see also bode Produces a minimal realization of a system (forces pole/zero cancellations)

norm

Norm of a vector Draw the Nyquist plot, see also lnyquist. Note this command was written to replace the MATLAB standard command nyquist to get more accurate Nyquist plots. The observability matrix, see also ctrb Returns a vector or matrix of ones, see also zeros Compute the K matrix to place the poles of A-BK, see also acker Draw a plot, see also figure, axis, subplot. Returns the characteristic polynomial Polynomial evaluation Print the current plot (to a printer or postscript file) Pole-zero map of linear systems Find the number of linearly independent rows or columns of a matrix Returns the real part of a complex number, see also imag Find the value of k and the poles at the selected point Draw the root locus Find the roots of a polynomial Find the scale factor for a full-state feedback system Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing of tick marks on the axes Generate grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also sigrid, zgrid Generate grid lines of constant settling time (sigma), see also sgrid, zgrid Gives the dimension of a vector or matrix, see also length Square root Create state-space models or convert LTI model to state space, see also tf

nyquist1

obsv ones place plot poly polyval print pzmap rank real rlocfind rlocus roots rscale set

sgrid sigrid size sqrt ss

ssdata stairs step subplot text tf tfdata title wbw

Access to state-space data. See also tfdata Stairstep plot for discrete response Plot the step response, see also impulse, lsim Divide the plot window up into pieces, see also plot, figure Add a piece of text to the current plot, see also title, xlabel, ylabel, gtext Creation of transfer functions or conversion to transfer function, see also ss Access to transfer function data, see also ssdata Add a title to the current plot Returns the bandwidth frequency given the damping ratio and the rise or settling time. Add a label to the horizontal/vertical axis of the current plot, see also title, text, gtext Returns a vector or matrix of zeros Generates grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also sgrid, sigrid

xlabel/ylabel zeros zgrid

Introduction to MATLAB Functions


When entering a command such as roots, plot, or step into MATLAB what you are really doing is running an m-file with inputs and outputs that has been written to accomplish a specific task. These types of m-files are similar to subroutines in programming languages in that they have inputs (parameters which are passed to the m-file), outputs (values which are returned from the m-file), and a body of commands which can contain local variab. MATLAB calls these m-files functions. You can write your own functions using the function command. The new function must be given a filename with a '.m' extension. This file should be saved in the same directory as the MATLAB software, or in a directory which is contained in MATLAB's search path. The first line of the file should contain the syntax for this function in the form:
function [output1,output2] = filename(input1,input2,input3)

A function can input or output as many variables are needed. The next few lines contain the text that will appear when the help filename command is evoked. These lines are optional, but must be entered using % in front of each line in the same way that you include comments in an ordinary m-file. Finally, below the help text, the actual text of the function with all of the commands is included. One suggestion would be to start with the line:
error(nargchk(x,y,nargin));

The x and y represent the smallest and largest number of inputs that can be accepted by the function; if more or less inputs are entered, an error is triggered. Functions can be rather tricky to write, and practice will be necessary to successfully write one that will achieve the desired goal. Below is a simple example of what the function, add.m, might look like.
function [var3] = add(var1,var2) %add is a function that adds two numbers var3 = var1+var2;

If you save these three lines in a file called "add.m" in the M ATLAB directory, then you can use it by typing at the command line:
y = add(3,8)

Obviously, most functions will be more complex than the one demonstrated here. This example just shows what the basic form looks like. Look at the

functions created for this tutorial listed below, or at the functions in the toolbox folder in the MATLABsoftware (for more sophisticated examples), or try help function for more information.

Functions Created for this Set of Tutorials


lnyquist.m | nyquist1.m | sigrid.m | wbw.m

Introduction to M-files
What is an m-file?

An m-file, or script file, is a simple text file where you can place MATLAB commands. When the file is run, M ATLAB reads the commands and executes them exactly as it would if you had typed each command sequentially at the MATLAB prompt. All m-file names must end with the extension '.m' (e.g. plot.m). If you create a new m-file with the same name as an existing m-file, MATLAB will choose the one which appears first in the path order (help path for more information). To make life easier, choose a name for your m-file which doesn't already exist. To see if a filename.m exists, type help filename at the MATLAB prompt.
Why use m-files?

For simple problems, entering your requests at the MATLAB prompt is fast and efficient. However, as the number of commands increases or trial and error is done by changing certain variab or values, typing the commands over and over at the MATLABprompt becomes tedious. M-files will be helpful and almost necessary in these cases.
How to create, save or open an m-file?

If you are using PC or Mac: To create an m-file, choose New from the File menu and select m-file. This procedure brings up a text editor window in which you can enter MATLAB commands. To save the m-file, simply go to the File menu and choose Save (remember to save it with the '.m' extension). To open an existing m-file, go to the File menu and choose Open . If you are using Unix: To create an m-file, use your favorite text editor (pico, nedit, vi, emacs, etc.) to create a file with .m extension (e.p. filename.m).
How to run the m-file?

After the m-file is saved with the name filename.m in the MATLAB folder or directory, you can execute the commands in the m-file by simply typing filename at the MATLAB prompt.

If you don't want to run the whole m-file, you can just copy the part of m-file that you want to run and paste it at the MATLAB prompt.

Plotting in MATLAB
Plot aesthetics Subplotting Changing the axis Adding text One of the most important functions in MATLAB is the plot function. Plot also happens to be one of the easiest functions to learn how to use. The basic format of the function is to enter the following command in the MATLAB command window or into a m-file.
plot(x,y)

This command will plot the elements of vector x on the horizontal axis of a figure, and the elements of the vector y on the vertical axis of the figure. The default is that each time the plot command is issued, the current figure will be erased; we will discuss how to override this below. If we wanted to plot the simple, linear formula:
y=3x

We could create a m-file with the following lines of code:


x = 0:0.1:100; y = 3*x; plot(x,y)

which will generate the following plot,

One thing to keep in mind when using the plot command is that the vectors x and y must be the same length. The other dimension can vary. M ATLAB can plot a 1 x n vector versus a n x 1 vector, or a 1 x n vector versus a 2 x n matrix (you will get two lines), as long as n is the same for both vectors. The plot command can also be used with just one input vector. In that case the vector columns are plotted versus their indices (the vector 1:1:n will be used for the horizontal axis). If the input vector contains complex numbers, MATLAB plots the real part of each element (on the x-axis) versus the imaginary part (on the y-axis).

Plot aesthetics
The color and point marker can be changed on a plot by adding a third parameter (in single quotes) to the plot command. For example, to plot the above function as a red, dotted line, the m-file should be changed to:
x = 0:0.1:100; y = 3*x; plot(x,y,'r:')

The plot now looks like:

The third input consists of one to three characters which specify a color and/or a point marker type. The list of colors and point markers is as follows:
y m c r g b w k yellow magenta cyan red green blue white black . o x + * s d v ^ < > point circle x-mark plus star square diamond triangle triangle triangle triangle : -. -solid dotted dashdot dashed

(down) (up) (left) (right)

p h

pentagram hexagram

You can plot more than one function on the same figure. Let's say you want to plot a sine wave and cosine wave on the same set of axes, using a different color and point marker for each. The following m-file could be used to do this:
x = linspace(0,2*pi,50); y = sin(x); z = cos(x); plot(x,y,'r', x,z,'gx')

You will get the following plot of a sine wave and cosine wave, with the sine wave in a solid red line and the cosine wave in a green line made up of x's:

By adding more sets of parameters to plot, you can plot as many different functions on the same figure as you want. When plotting many things on the same graph it is useful to differentiate the different functions based on color and point marker. This same effect can also be achieved using the hold on and hold off commands. The same plot shown above could be generated using the following m-file:
x = linspace(0,2*pi,50); y = sin(x); plot(x,y,'r') z = cos(x); hold on plot(x,z,'gx') hold off

Always remember that if you use the hold on command, all plots from then on will be generated on one set of axes, without erasing the previous plot, until the hold off command is issued.

Subplotting
More than one plot can be put on the same figure using the subplot command. The subplot command allows you to separate the figure into as many plots as desired, and put them all in one figure. To use this command, the following line of code is entered into the MATLAB command window or an m-file:
subplot(m,n,p)

This command splits the figure into a matrix of m rows and n columns, thereby creating m*n plots on one figure. The p'th plot is selected as the currently active plot. For instance, suppose you want to see a sine wave, cosine wave, and tangent wave plotted on the same figure, but not on the same axis. The following m-file will accomplish this:
x y z w = = = = linspace(0,2*pi,50); sin(x); cos(x); tan(x);

subplot(2,2,1) plot(x,y) subplot(2,2,2) plot(x,z) subplot(2,2,3) plot(x,w)

As you can see, there are only three plots, even though we created a 2 x 2 matrix of 4 subplots. We did this to show that you do not have to fill all of the subplots you have created, but MATLAB will leave a spot for every position in the matrix. We could have easily made another plot using the subplot(2,2,4) command. The subplots are arranged in the same manner as you would read a book. The first subplot is in the top left corner, the next is to its right. When all the columns in that row are filled, the left-most column on the next row down is filled (all of this assuming you fill your subplots in order i.e. 1, 2, 3,..).

One thing to note about the subplot command is that every plot command issued later will place the plot in whichever subplot position was last used, erasing the plot that was previously in it. For example, in the m-file above, if a plot command was issued later in the m-file, it would be plotted in the third position in the subplot, erasing the tangent plot. To solve this problem, the figure should be cleared (using clf), or a new figure should be specified (using figure).

Changing the axis


Now that you have found different ways to plot functions, you can customize your plots to meet your needs. The most important way to do this is with the axis command. The axis command changes the axis of the plot shown, so only the part of the axis that is desirable is displayed. The axis command is used by entering the following command right after the plot command (or any command that has a plot as an output):
axis([xmin, xmax, ymin, ymax])

For instance, suppose want to look at a plot of the function you enter the following into MATLAB
t=0:0.01:5; y=exp(5*t)-1; plot(t,y)

. If

you should have the following plot:

As you can see, the plot goes to infinity. Looking at the y-axis (scale: 8e10), it is apparent that not much can be seen from this plot. To get a better idea of what is going on in this plot, let's look at the first second of this function. Enter the following command into the MATLAB command window.
axis([0, 1, 0, 50])

and you should get the following plot:

Now this plot is much more useful. You can see more clearly what is going on as the function moves toward infinity. You can customize the axis to your needs. When using the subplot command, the axis can be changed for each subplot by issuing an axis command before the next subplot command. There are more uses of the axis command which you can see if you type help axis in the MATLAB command window.

Adding text
Another thing that may be important for your plots is labeling. You can give your plot a title (with the title command), x-axis label (with the xlabel command), y-axis label (with the ylabel command), and put text on the actual plot. All of the above commands are issued after the actual plot command has been issued. A title will be placed, centered, above the plot with the command: title('title string'). The x-axis label is issued with the following command: xlabel('x-axis string'). The y-axis label is issued with the following command: ylabel('y-axis string'). Furthermore, text can be put on the plot itself in one of two ways: the text command and the gtext command. The first command involves knowing the coordinates of where you want the text string. The command is text(xcor,ycor,'textstring'). To use the other command, you do not need to know the exact coordinates. The command is gtext('textstring'), and then you just move the cross-hair to the desired location with the mouse, and click on the position you want the text placed.

To further demonstrate labeling, take the exponential plot from above. Assuming that you have already changed the axis, copying the following lines of text after the axis command will put all the labels on the plot:
title('exponential function') xlabel('time (sec)') ylabel('output') gtext('unnecessary labeling')

The text "unnecessary labeling" was placed right above the position that was clicked on. The plot should look like the following:

Other commands that can be used with the plot command are:

(clears the current plot, so it is blank) figure (opens a new figure to plot on, so the previous figure is saved) close (closes the current figure window) loglog (same as plot, except both axes are log base 10 scale) semilogx (same as plot, except x-axis is log base 10 scale) semilogy (same as plot, except y-axis is log base 10 scale) grid (adds grid line to your plot)
clf

Of course this is not a complete account of plotting with M ATLAB, but it should give you a nice start.

Step Response in M ATLAB


The step function is one of most useful functions in MATLAB for control design. Given a system representation, the response to a step input can immediately be plotted. A step input can be described as a change in the input from zero to a finite value at time t = 0. By default, the step command performs a unit step (i.e. the input goes from zero to one at time t = 0). The basic command to use the step function is the following:
step(sys)

This command will produce a series of step response plots, all on the same figure. A plot will be made for each input and output combination. Most problems you will come across in the beginning will be SISO or Single-Input, Single-Output. In this case there will only be one plot made, but the step command handles these problems in the same manner as a SIMO or Single-Input, Multiple-Output. For example, suppose you want to model a mechanical system consisting of a mass, spring, and damper, with an applied force. You have come up with the transfer function shown below. You wish to see what the system response to unit step input is (an applied force of 1N). To model this, enter the following into MATLAB:
M = num den sys 1; K = 10; B = 2; = 1; = [M B K]; = tf(num,den);

step(sys)

You should see the following figure:

This figure shows the output response, which is the position of the mass. You can see that in steady-state, the mass has moved 0.1m (the spring force balances the applied force). The system is underdamped and has an overshoot. That's about it for the basic use of the step command. If you are interested, or if you need to use a step command in a more complex format, continue reading.
Changing the magnitude of the step

So far, we have only dealt with unit step inputs. Suppose the input to our system was not 1 Newton but fact 100N. The step command can accommodate this by multiplying the system by 100. For the example above, you should get the following plot
step(100*sys);

The plot looks similar to the one above it except that the scale on the y-axis is different.
Specifying the time scale

Both the step response for a set of state space equations or for a transfer function can be plotted with a user-supplied time vector. This vector will specify the time interval over which the step response will be calculated. If the vector is spaced at small time intervals, the plot will look smoother. The commands to use the time vector are
step(sys,t)

In the above two plots, only the first 6 seconds of the response are shown. Suppose that the first 10 seconds need to be displayed. A time vector can be

created to compute the step response over this range. Adding the following commands to above m-file in MATLAB:
t=0:0.1:10; step(sys,t)

you should get the following plot:

As you can see, the plot goes for 10 seconds.


Saving the response

The final note about the step command is that all of the above variations can be used with a left hand arguments. There are two ways to invoke the left hand arguments, depending on whether or not the time vector was used in the step command. If the time vector is used, the command is:
[y,t] = step(sys); or [y,t] = step(sys,t);

If the system is in state-space form, all of the states can be returned:


[y,t,x] = step(sys);

The y vector contains the output response. It has as many columns as outputs and as many rows as elements in the time vector, t. The x vector contains the state response. It has as many columns as states and as many rows as elements in the time vector, t. When used with left hand arguments, no plot is drawn for the step command. You will usually want to put a

semicolon after the step command when you invoke it with left-hand arguments; otherwise, MATLAB will print out the entire output, state, and time vectors to the command window. You can plot the output response using plot(t,y) or the state response using plot(t,x).

Steady-State Error
Calculating steady-state errors System type and steady-state error Example: Meeting steady-state error requirements Steady-state error is defined as the difference between the input and output of a system in the limit as time goes to infinity (i.e. when the response has reached the steady state). The steady-state error will depend on the type of input (step, ramp, etc) as well as the system type (0, I, or II).

Note: Steady-state error analysis is only useful for stable systems. You should always check the system for stability before performing a steady-state error analysis. Many of the techniques that we present will give an answer even if the system is unstable; obviously this answer is meaningless for an unstable system.

Calculating steady-state errors


Before talking about the relationships between steady-state error and system type, we will show how to calculate error regardless of system type or input. Then, we will start deriving formulas we will apply when we perform a steady state-error analysis. Steady-state error can be calculated from the open or closed-loop transfer function for unity feedback systems. For example, let's say that we have the following system:

which is equivalent to the following system:

We can calculate the steady state error for this system from either the open or closed-loop transfer function using the final value theorem (remember that this theorem can only be applied if the denominator has no poles in the righthalf plane):

Now, let's plug in the Laplace transforms for different inputs and find equations to calculate steady-state errors from open-loop transfer functions given different inputs:

Step Input (R(s) = 1/s):

Ramp Input (R(s) = 1/s^2):

Parabolic Input (R(s) = 1/s^3):

When we design a controller, we usually want to compensate for disturbances to a system. Let's say that we have the following system with a disturbance:

we can find the steady-state error for a step disturbance input with the following equation:

Lastly, we can calculate steady-state error for non-unity feedback systems:

By manipulating the blocks, we can model the system as follows:

Now, simply apply the equations we talked about above.

System type and steady-state error


If you refer back to the equations for calculating steady-state errors for unity feedback systems, you will find that we have defined certain constants ( known as the static error constants). These constants are the position constant (Kp), the velocity constant (Kv), and the acceleration constant (Ka). Knowing the value of these constants as well as the system type, we can predict if our system is going to have a finite steady-state error. First, let's talk about system type. The system type is defined as the number of pure integrators in a system. That is, the system type is equal to the value of n when the system is represented as in the following figure:

Therefore, a system can be type 0, type 1, etc. Now, let's see how steady state error relates to system types: Type 0 systems
Steady State Error Formula Static Error Constant Error Step Input 1/(1+Kp) Kp = constant 1/(1+Kp) Step Input Ramp Input 1/Kv Kv = 0 infinity Ramp Input Parabolic Input 1/Ka Ka = 0 infinity Parabolic Input

Type 1 systems

Steady State Error Formula Static Error Constant Error

1/(1+Kp) Kp = infinity 0 Step Input 1/(1+Kp)

1/Kv Kv = constant 1/Kv

1/Ka Ka = 0 infinity

Type 2 systems
Steady State Error Formula Static Error Constant Error

Ramp Input Parabolic Input 1/Kv 1/Ka Ka = constant 1/Ka

Kp = infinity Kv = infinity 0 0

Example: Meeting steady-state error requirements


Given the following system,

where G(s) is:


K*(s + 3)(s + 5) -------------------------s (s + 7)(s + 8)

find the value of K so that there is 10% steady state error in open loop. Since this system is type 1, there will be no steady-state error for a step input and an infinite error for a parabolic input. The only input that will yield a finite steady-state error in this system is a ramp input. Let's look at the ramp input response for a gain of 1:
num = conv( [1 5], [1 3]); den = conv(conv([1,7],[1 8]),[1,0]); plant = tf(num,den); sysC = feedback(plant,1); t = 0:0.1:50; u = t; [y,t,x] = lsim(sysC,u,t); plot(t,y,'y',t,u,'m') xlabel('Time(secs)') ylabel('Amplitude') title('Input-purple, Output-yellow')

The steady-state error for this system is very large, since we can see that an input of time = 20 gives us an output with amplitude of approximately 16. We will talk about this in further detail. We know from our problem statement that the steady state error must be 0.1. Therefore, we can solve the problem following these steps:

Let's see the ramp input response for K = 37.33:


k =37.33 ; num = conv( [1 5], [1 3]); den = conv(conv([1,7],[1 8]),[1,0]); plant = tf(num,den); sysC = feedback(k*plant,1); t = 0:0.1:50; u = t; [y,t,x] = lsim(sysC,u,t); plot(t,y,'y',t,u,'m') xlabel('Time(secs)') ylabel('Amplitude') title('Input-purple, Output-yellow')

In order to get a better view, we must zoom in on the response. We choose to zoom in between 40 and 41 because we will be sure that the system has reached steady state by then and we will also be able to get a good view of the input and the output.
axis([40,41,40,41])

The amplitude = 40 at t = 40 for our input, and time = 40.1 for our output. However, since these are parallel lines in steady state, we can also say that when time = 40 our output has an amplitude of 39.9, giving us a steady-state error of 10%. Let's zoom in further on this plot and confirm our statement:
axis([39.9,40.1,39.9,40.1])

Now let's modify the problem a little bit and say that our system looks as follows:

Our G(s) is the same, but now we want zero steady-state error for a ramp input. From our tables, we know that a system of type 2 gives us zero steady-state error for a ramp input. Therefore, we can get zero steady-state error by simply

adding an integrator (a pole at the origin) Let's view the ramp input response for a step input if we add an integrator and use a gain of one:
num = conv( [1 5], [1 3]); den = conv(conv([1,7],[1 8]),[1,0]); plant = tf(num,den); numc = 1; denc = [1 0]; contr = tf(numc,denc); sysC = feedback(contr*plant,1); t = 0:0.1:250; u = t; [y,t,x] = lsim(sysC,u,t); plot(t,y,'y',t,u,'m') xlabel('Time(secs)') ylabel('Amplitude') title('Input-purple, Output-yellow')

As you can see, the response is not the most desirable one (we can see oscillations at 100secs, but you may have to zoom in to see them). However, at steady state we have zero steady-state error. Let's zoom in at 240 secs. (trust me, it doesn't reach steady state until then):
axis([239.9,240.1,239.9,240.1])

As you can see, the steady-state error is zero. Feel free to zoom in at different areas on the diagram and observe how the response approaches steady state.

Pole-Zero Cancellation
When an open-loop system has right-half-plane poles (in which case the system is unstable), one idea to alleviate this problem is to add zeros at the same locations as the poles, to cancel the unstable poles. Unfortunately, this method is unreliable. The problem is that when the added zero does not exactly cancel the pole (which is always the case in real life), a part of the root locus will be trapped in the right-half plane. This causes the closed-loop response to be unstable. The following example demonstrates this concept. Suppose we have an open-loop transfer function:

Create a new m-file, and enter:


num = 1; den = [3 2 -1]; plant = tf(num,den); rlocus(plant)

This should give you the root locus of this open-loop system: Run the m-file and you should get the following root locus plot:

We see that one of the open-loop poles is at the right-half plane. The closedloop response will be unstable if the gain is selected such that one of the poles is in the right half plane. We can make this system stable by choosing the correct gain, but let's see if we can make the system stable by doing a polezero cancellation. Inspecting the root locus above, we see that the unstable pole is at the vicinity of 0.3. Delete the rlocus command, and add the following lines into your m-file to add a zero at -0.3:

z = -0.3; zero = tf([1,z],1); rlocus(zero*plant)

From the new root locus you can see that the unstable pole has almost been canceled. Now let's see what the closed-loop response look like. Add the following to the end of your m-file:
sys_cl = feedback(zero*plant,1); step(sys_cl,100)

The system is still unstable. The reason for this is that the zero does not exactly cancel the unstable pole. Can we make the system stable by moving the zero so that it's exactly on the pole? From the original transfer function, you know that the open-loop pole is actually at 1/3. What if we put our zero at exactly 1/3? Go back to the m-file and change Zero to 1/3:
z = -1/3

Rerun the m-file, and you should get the following root locus plot:

This time we see that the zero is right on the unstable pole (you may use zoom command to zoom into the plot, to see that the zero is exactly on the pole). What does the closed-loop response look like now, is it stable? Look at the step response plot to find out:

No, it's still unstable! The response takes much longer to blow up, so we have almost canceled the effect, but almost is not good enough when the question is stability. A system which is "almost stable" is still unstable, and its response will go to infinity. From the example above, we see that the pole-zero cancellation is theoretically okay, but practically unobtainable. A solution to this example can be found using the method introduced in the root locus tutorial. Noted that an improper system (a system with more zeros than poles) is not realizable using any physical system. In this example, we use only one zero for simplicity.

Plotting Frequency Response


In order to illustrate the plotting of G(jw), we will generate our own plot of G(j*w)and compare it with the Bode plots and the Nyquist diagram. If we run the following m-file, we will see the points that comprise G(jw), in particular the point corresponding to G(j*3).
%define the transfer function num = conv([1,4],[1 6]); den = conv([1,-3],[1 -5]); %create a frequency vector clf w = logspace(-1,2,100); hold on %plot a '+' for each point corresponding to G(jw) for i = 1:100 plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+') end %plot a green 'X' for frequency of 3rad/s plot(polyval(num,j*3)/polyval(den, j*3), 'xg') %plot vector from origin to this point n= polyval(num,j*3)/polyval(den, j*3); x = [0,real(n)]; y = [0,imag(n)]; plot(x,y, '-g') %find magnitude and phase Mag = abs(n); Phase = 180 +360*atan(imag(n)/real(n))/(2*pi); %find gain Gain = 20*log10(Mag); grid Mag, Phase, Gain

The image should look similar to this:

Please note that each yellow cross represents the transfer function evaluated at a specific frequency and that only positive frequencies are used. Also note

the point and vector associated with a frequency of 3 rad/s (green). In the MATLAB command window, you should see the Magnitude, Phase, and Gain (in dB) associated with this vector:
Note: a decibel is defined as 20*log10 ( |G(j*w| )
Mag = 1.3558 Phase = 139.3987 Gain = 2.6440

Bode representation
The Bode plots take each one of the points on the above plot and breaks it down into magnitude and phase. The magnitude is then plotted as gain in decibels and the phase is plotted in degrees. The frequency (on the independent axis) is plotted on a logarithmic scale. Let's take a look at the Bode plots for this function and see if our answers match.
bode(num,den)

If you look at the plots at a frequency of 3rad/s you will see the magnitude is a little over 2.5 dB and the phase is around 140 degrees. This agrees with our previous results.

Nyquist Representation

Now that we know where Bode plots come form, let's see where Nyquist plots come from. The Nyquist diagram is basically a plot of G(j*w). However, both positive and negative frequencies of the contour we showed previously are taken into account. Let's plot the Nyquist diagram on top of our G(j*w) plot (this time, we will include the negative frequencies as well).
%define the transfer function num = conv([1,4],[1 6]); den = conv([1,-3],[1 -5]); %create a frequency vector similar to the one described above w = logspace(-1,2,100); negw = -1*w; clf hold on %plot a '+' for each point corresponding to G(jw) for i = 1:100 plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+') plot(polyval(num,j*negw(1,i))/polyval(den, j*negw (1,i)), '+') end %draw Nyquist diagram on top to compare nyquist(num,den) hold off

A perfect match! Also note that the negative frequencies produce a mirror image across the real axis of the positive frequency response.

Sample Bode Plots


Let's say that we have the following system:

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

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

bode([1 0], 1) s

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

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

bode(1,[ 1, 10]) 1

-----s + 10

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

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

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

Bandwidth Frequency
As we mentioned before, we can relate bandwidth frequency to closed-loop natural frequency and damping ratio. Thus, we can relate bandwidth frequency to damping ratio and peak or settling time with the following equations.

Settling Time

In order to make our life easier, we usually plot these equations instead of plugging in the values:

Peak Time

Again, we usually look at the graph instead of plugging in the values.

MATLAB Code
Below is the function wbw.m. This function will return the approximate bandwidth frequency, given the damping ratio and the rise or settling time. To use wbw.m in MATLAB, enter wbw at the command line. You will be prompted for a damping ratio. You will then be asked to enter 0 if you are using a settling time or 1 if you are using a peak time. Finally you will be asked for the desired settling or peak time, and the bandwidth frequency will be returned. Copy the following text into a file wbw.m, and save it where MATLAB will be able to find it (such as in the directory that you run MATLAB from).

function[] = wbw() DR = input('Damping Ratio? '); n = 0; n = input('Settling Time(0) or Peak Time(1)? if n == 0 ts = input('Settling Time? '); temp1 = sqrt((4*DR^4) - (4*DR^2) +2); temp2 = 1- (2*DR^2); temp3 = 4/(ts*DR); Wbw = temp3*sqrt(temp1 + temp2) end if n ==1 ts = input('Peak Time? '); temp1 = sqrt((4*DR^4) - (4*DR^2) +2); temp2 = 1- (2*DR^2); temp3 = ts*sqrt( 1- DR^2); temp4 = pi/temp3; Wbw = temp4*sqrt(temp1 + temp2) end

');

Function Sigrid
plotting the sigma requirement on the root locus
Below is the function sigrid.m. This function will plot the sigma requirement on the same graph as another plot, such as an rlocus. To use sigrid.m in MATLAB enter sigrid(sigma). Copy the following text into a file sigrid.m, and put it in the same directory as the MATLAB software, or in a directory which is contained in MATLAB's search path.

function[ ] = sigrid(sig) %SIGRID Generate s-plane grid lines for a root locus or pole-zero map. % % SIGRID generates a grid over an existing continuous s-plane root % locus or pole-zero map. Lines of constant sigma are drawn in. % To be used with SGRID if sigma, zeta, and Wn requirements are required % simultaneously. Can also be used by itself. % % See also: RLOCUS, ZGRID, SGRID, and PZMAP. error(nargchk(1,1,nargin)); hold on %Plot sigma line limits = axis; mx=limits(1,4); mn=limits(1,3); stz=abs(mx)+abs(mn); st=stz/50; im=mn:st:mx; lim=length(im); for i=1:lim re(i)=-sig; end re(:); plot(re,im,'.') hold off return

Function lnyquist:
plotting the Nyquist on a log-base-2 scale
Below is the function lnyquist.m. This function is a modified version of MATLAB's nyquist command, and has the same attributes as the original, with a few improvements. lnyquist.m plots (log2(1 + |G(jw)|), angle(G(jw))) in polar coordinates. By taking the log of the magnitude, the magnitude scale is compressed and the overall shape of the Nyquist plot is easier to see on the screen. We use log base 2 and add one to the magnitude so as to preserve the key attributes of the -1 point for the Nyquist plot. lnyquist also takes poles on the imaginary axis into account when creating the Nyquist plot, and plots around them. Copy the following text into a file lnyquist.m. Put it in the same directory as the MATLAB software, or in a directory which is contained in MATLAB's search path.

function [reout,imt,w] = lnyquist(a,b,c,d,iu,w) %LNYQUIST Nyquist frequency response for continuous-time linear systems. % % This Version of the NYQUIST Command takes into account poles at the % jw-axis and loops around them when creating the frequency vector in order % to produce the appropriate Nyquist Diagram (The NYQUIST command does % not do this and therefore produces an incorrect plot when we have poles in the % jw axis). % % NOTE: This version of LNYQUIST does not account for pole-zero % cancellation. Therefore, the user must simplify the transfer function before using % this command. % % LNYQUIST(A,B,C,D,IU) produces a Nyquist plot from the single input % IU to all the outputs of the system: % . -1 % x = Ax + Bu G(s) = C(sI-A) B + D

% y = Cx + Du RE(w) = real(G(jw)), IM(w) = imag(G(jw)) % % The frequency range and number of points are chosen automatically. % % LNYQUIST(NUM,DEN) produces the Nyquist plot for the polynomial % transfer function G(s) = NUM(s)/DEN(s) where NUM and DEN contain % the polynomial coefficients in descending powers of s. % % LNYQUIST(A,B,C,D,IU,W) or LNYQUIST(NUM,DEN,W) uses the usersupplied % freq. vector W which must contain the frequencies, in radians/sec, % at which the Nyquist response is to be evaluated. When invoked % with left hand arguments, % [RE,IM,W] = LNYQUIST(A,B,C,D,...) % [RE,IM,W] = LNYQUIST(NUM,DEN,...) % returns the frequency vector W and matrices RE and IM with as many % columns as outputs and length(W) rows. No plot is drawn on the % screen. % See also: LOGSPACE,MARGIN,BODE, and NICHOLS. % J.N. Little 10-11-85 % Revised ACWG 8-15-89, CMT 7-9-90, ACWG 2-12-91, 6-21-92, % AFP 2-23-93 % WCM 8-30-97 % % ******************************************************************** % Modifications made to the nyquist - takes into account poles on jw axis. % then goes around these to make up frequency vector % if nargin==0, eval('exresp(''nyquist'')'), return, end % --- Determine which syntax is being used --nargin1 = nargin; nargout1 = nargout; if (nargin1==1), % System form without frequency vector [num,den]=tfdata(a,'v'); z = roots(num); p = roots(den); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30);

[ny,nn] = size(num); nu = 1; %error('Wrong number of input arguments.'); elseif (nargin1==2), if(isa(a,'ss')|isa(a,'tf')|isa(a,'zpk')) % System with frequency vector [num,den]=tfdata(a,'v'); w = b; else % Transfer function form without frequency vector num = a; den = b; z = roots(num); p = roots(den); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30); end [ny,nn] = size(num); nu = 1; elseif (nargin1==3), % Transfer function form with frequency vector num = a; den = b; w = c; [ny,nn] = size(num); nu = 1; elseif (nargin1==4), % State space system, w/o iu or frequency vector error(abcdchk(a,b,c,d)); [num,den] = ss2tf(a,b,c,d); [z,p,k]= ss2zp(a,b,c,d); [num,den] = zp2tf(z,p,k); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(a,b,c,d,30); nargin1 = 2;%[iu,nargin,re,im]=mulresp('nyquist',a,b,c,d,w,nargout1,0); %if ~iu, if nargout, reout = re; end, return, end [ny,nu] = size(d); elseif (nargin1==5), % State space system, with iu but w/o freq. vector error(abcdchk(a,b,c,d)); z = tzero(a,b,c,d); p = eig(a); zp = [z;p];

wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(a,b,c,d,30); [ny,nu] = size(d); else error(abcdchk(a,b,c,d)); [ny,nu] = size(d); end if nu*ny==0, im=[]; w=[]; if nargout~=0, reout=[]; end, return, end % ********************************************************************* % depart from the regular nyquist program here % now we have a frequency vector, a numerator and denominator % now we create code to go around all poles and zeroes here. if (nargin1==5) | (nargin1 ==4) | (nargin1 == 6) [num,den]=ss2tf(a,b,c,d); end tol = 1e-6; %defined tolerance for finding imaginary poles z = roots(num); p = roots(den); % ***** If all of the poles are at the origin, just move them a tad to the left*** if norm(p) == 0 if(isempty(z)) tad = 1e-1; else tad = min([1e-1; 0.1*abs(z)]); end length_p = length(p); p = -tad*ones(length_p,1); den = den(1,1)*[1 tad]; for ii = 2:length_p den = conv(den,[1 tad]); end zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30); end

zp = [z;p]; % combine the zeros and poles of the system nzp = length(zp); % number of zeros and poles ones_zp=ones(nzp,1); %Ipo = find((abs(real(p))<1e-6) & (imag(p)>=0)) %index poles with zero real part + non-neg imag part Ipo = find((abs(real(p)) < tol) & (imag(p)>=0)); %index poles with zero real part + non-neg imag part if ~isempty(Ipo) % % **** only if we have such poles do we do the following:************************* po = p(Ipo); % poles with 0 real part and non-negative imag part % check for distinct poles [y,ipo] = sort(imag(po)); % sort imaginary parts po = po(ipo); dpo = diff(po); idpo = find(abs(dpo)>tol); idpo = [1;idpo+1]; % indexes of the distinct poles po = po(idpo); % only distinct poles are used nIpo = length(idpo); % # of such poles originflag = find(imag(po)==0); % locate origin pole s = []; % s is our frequency response vector w = sqrt(-1)*w; % create a jwo vector to evaluate all frequencies with for ii=1:nIpo % for all Ipo poles [nrows,ncolumns]=size(w); if nrows == 1 w = w.'; % if w is a row, make it a column end; if nIpo == 1 r(ii) = .1; else % check distances to other poles and zeroes pdiff = zp-po(ii)*ones_zp; % find the differences between % poles you are checking and other poles and zeros ipdiff = find(abs(pdiff)>tol); % ipdiff is all nonzero differences r(ii)=0.2*min(abs(pdiff(ipdiff))); % take half this difference r(ii)=min(r(ii),0.1); % take the minimum of this diff.and .1 end; t = linspace(-pi/2,pi/2,25); if (ii == originflag) t = linspace(0,pi/2,25); end; % gives us a vector of points around each Ipo s1 = po(ii)+r(ii)*(cos(t)+sqrt(-1)*sin(t)); % detour here s1 = s1.'; % make sure it is a column % Now here I reconstitute s - complex frequency - and % evaluate again. bottomvalue = po(ii)-sqrt(-1)*r(ii); part if (ii == originflag) % if this is an origin point bottomvalue = 0; end; % take magnitude of imag

topvalue = po(ii)+sqrt(-1)*r(ii); % the top value where detour stops nbegin = find(imag(w) < imag(bottomvalue)); % nnbegin = length(nbegin); % find all the points less than encirclement if (nnbegin == 0)& (ii ~= originflag) % around jw root sbegin = 0 else sbegin = w(nbegin); end; nend = find(imag(w) > imag(topvalue)); % find all points greater than nnend = length(nend); % encirclement around jw root if (nnend == 0) send = 0 else send = w(nend); end w = [sbegin; s1; send]; % reconstituted half of jw axis end else w = sqrt(-1)*w; end %end % this ends the loop for imaginary axis poles % ************************************************************* % back to the regular nyquist program here % Compute frequency response if (nargin1==1)|(nargin1==2)|(nargin1==3) gt = freqresp(num,den,w); else gt = freqresp(a,b,c,d,iu,w); end % *********************************************************** nw = length(gt); mag = abs(gt); % scaling factor added ang = angle(gt); mag = log2(mag+1); % scale by log2(mag) throughout for n = 1:nw h(n,1) = mag(n,1)*(cos(ang(n,1))+sqrt(1)*sin(ang(n,1))); end; % recalculate G(jw) with scaling factor gt = h; % *********************************************************** ret=real(gt); imt=imag(gt); % If no left hand arguments then plot graph. if nargout==0, status = ishold; plot(ret,imt,'r-',ret,-imt,'g--') % plot(real(w),imag(w)) % modifications added here %******************************************* set(gca, 'YLimMode', 'auto') limits = axis; % Set axis hold on because next plot command may rescale

set(gca, 'YLimMode', 'auto') set(gca, 'XLimMode', 'manual') hold on % Make arrows for k=1:size(gt,2), g = gt(:,k); re = ret(:,k); im = imt(:,k); sx = limits(2) - limits(1); [sy,sample]=max(abs(2*im)); arrow=[-1;0;-1] + 0.75*sqrt(-1)*[1;0;-1]; sample=sample+(sample==1); reim=diag(g(sample,:)); d=diag(g(sample+1,:)-g(sample-1,:)); % Rotate arrow taking into account scaling factors sx and sy d = real(d)*sy + sqrt(-1)*imag(d)*sx; rot=d./abs(d); % Use this when arrow is not horizontal arrow = ones(3,1)*rot'.*arrow; scalex = (max(real(arrow)) - min(real(arrow)))*sx/50; scaley = (max(imag(arrow)) - min(imag(arrow)))*sy/50; arrow = real(arrow)*scalex + sqrt(-1)*imag(arrow)*scaley; xy =ones(3,1)*reim' + arrow; xy2=ones(3,1)*reim' - arrow; [m,n]=size(g); hold on plot(real(xy),-imag(xy),'r-',real(xy2),imag(xy2),'g-') end xlabel('Real Axis'), ylabel('Imag Axis') limits = axis; % Make cross at s = -1 + j0, i.e the -1 point if limits(2) >= -1.5 & limits(1) <= -0.5 % Only plot if -1 point is not far out. line1 = (limits(2)-limits(1))/50; line2 = (limits(4)-limits(3))/50; plot([-1+line1, -1-line1], [0,0], 'w-', [-1, -1], [line2, line2], 'w-') end % Axis plot([limits(1:2);0,0]',[0,0;limits(3:4)]','w:'); plot(-1,0,'+k'); if ~status, hold off, end % Return hold to previous status return % Suppress output end %reout = ret; % plot(real(p),imag(p),'x',real(z),imag(z),'o');

Function nyquist1:
plotting Nyquist frequency response for continuous-time linear systems
Below is the function nyquist1.m. This function is a modified version of the nyquist command, and has all the same attributes as the original, with a few improvements. nyquist1.m takes poles on the imaginary axis into account when creating the Nyquist plot, and plots around them. Copy the following text into a file nyquist1.m, and put it in the same directory as the MATLAB software, or in a directory which is contained in M ATLAB's search path.

function [reout,imt,w] = nyquist1(a,b,c,d,iu,w) %NYQUIST1 Nyquist frequency response for continuous-time linear systems. % % This Version of the NYQUIST Command takes into account poles at the % jw-axis and loops around them when creating the frequency vector in order % to produce the appropriate Nyquist Diagram (The NYQUIST command does % not do this and therefore produces an incorrect plot when we have poles in the % jw axis). % % NOTE: This version of NYQUIST1 does not account for pole-zero % cancellation. Therefore, the user must simplify the transfer function before using % this command. % % NYQUIST(A,B,C,D,IU) produces a Nyquist plot from the single input % IU to all the outputs of the system: % . -1 % x = Ax + Bu G(s) = C(sI-A) B + D % y = Cx + Du RE(w) = real(G(jw)), IM(w) = imag(G(jw)) % % The frequency range and number of points are chosen automatically. % % NYQUIST1(NUM,DEN) produces the Nyquist plot for the polynomial % transfer function G(s) = NUM(s)/DEN(s) where NUM and DEN contain % the polynomial coefficients in descending powers of s. % % NYQUIST1(A,B,C,D,IU,W) or NYQUIST(NUM,DEN,W) uses the usersupplied

% freq. vector W which must contain the frequencies, radians/sec, % at which the Nyquist response is to be evaluated. invoked % with left hand arguments, % [RE,IM,W] = NYQUIST(A,B,C,D,...) % [RE,IM,W] = NYQUIST(NUM,DEN,...) % returns the frequency vector W and matrices RE and many % columns as outputs and length(W) rows. No plot is the % screen. % See also: LOGSPACE,MARGIN,BODE, and NICHOLS.

in When

IM with as drawn on

% J.N. Little 10-11-85 % Revised ACWG 8-15-89, CMT 7-9-90, ACWG 2-12-91, 6-21-92, % AFP 2-23-93 % WCM 8-31-97 % % ******************************************************************** % Modifications made to the nyquist - takes into account poles on jw axis. % then goes around these to make up frequency vector % if nargin==0, eval('exresp(''nyquist'')'), return, end % --- Determine which syntax is being used --nargin1 = nargin; nargout1 = nargout; if (nargin1==1), % System form without frequency vector [num,den]=tfdata(a,'v'); z = roots(num); p = roots(den); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30); [ny,nn] = size(num); nu = 1; %error('Wrong number of input arguments.'); elseif (nargin1==2), if(isa(a,'ss')|isa(a,'tf')|isa(a,'zpk')) % System with frequency vector [num,den]=tfdata(a,'v'); w = b; else % Transfer function form without frequency vector num = a; den = b; z = roots(num); p = roots(den);

zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30); end [ny,nn] = size(num); nu = 1; elseif (nargin1==3), % Transfer function form with frequency vector num = a; den = b; w = c; [ny,nn] = size(num); nu = 1; elseif (nargin1==4), % State space system, w/o iu or frequency vector error(abcdchk(a,b,c,d)); [num,den] = ss2tf(a,b,c,d); [z,p,k]= ss2zp(a,b,c,d); [num,den] = zp2tf(z,p,k); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(a,b,c,d,30); nargin1 = 2;%[iu,nargin,re,im]=mulresp('nyquist',a,b,c,d,w,nargout1,0); %if ~iu, if nargout, reout = re; end, return, end [ny,nu] = size(d); elseif (nargin1==5), % State space system, with iu but w/o freq. vector error(abcdchk(a,b,c,d)); z = tzero(a,b,c,d); p = eig(a); zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(a,b,c,d,30); [ny,nu] = size(d); else

error(abcdchk(a,b,c,d)); [ny,nu] = size(d); end if nu*ny==0, im=[]; w=[]; if nargout~=0, reout=[]; end, return, end % ********************************************************************* % depart from the regular nyquist program here % now we have a frequency vector, a numerator and denominator % now we create code to go around all poles and zeroes here. if (nargin1==5) | (nargin1 ==4) | (nargin1 == 6) [num,den]=ss2tf(a,b,c,d); end tol = 1e-6; %defined tolerance for finding imaginary poles z = roots(num); p = roots(den); % ***** If all of the poles are at the origin, just move them a tad to the left*** if norm(p) == 0 if(isempty(z)) tad = 1e-1; else tad = min([1e-1; 0.1*abs(z)]); end length_p = length(p); p = -tad*ones(length_p,1); den = den(1,1)*[1 tad]; for ii = 2:length_p den = conv(den,[1 tad]); end zp = [z;p]; wpos = zp(find(abs(zp)>0)); if(min(abs(p)) == 0) wstart = max(eps, 0.03*min([1;wpos])); else wstart = max(eps, 0.03*min(abs(zp))); end wstop = max([1000;30*wpos]); w = logspace(log10(wstart),log10(wstop),max(51,10*max(size(zp))+1)); %w = freqint2(num,den,30); end zp = [z;p]; % combine the zeros and poles of the system nzp = length(zp); % number of zeros and poles ones_zp=ones(nzp,1); Ipo = find((abs(real(p))< tol) & (imag(p)>=0)); %index poles with zero real part + non-neg imag part if ~isempty(Ipo) % % **** only if we have such poles do we do the following:************************* po = p(Ipo); % poles with 0 real part and non-negative imag part % check for distinct poles [y,ipo] = sort(imag(po)); % sort imaginary parts

po = po(ipo); dpo = diff(po); idpo = find(abs(dpo)> tol); idpo = [1;idpo+1]; % indexes of the distinct poles po = po(idpo); % only distinct poles are used nIpo = length(idpo); % # of such poles originflag = find(imag(po)==0); % locate origin pole s = []; % s is our frequency response vector w = sqrt(-1)*w; % create a jwo vector to evaluate all frequencies with for ii=1:nIpo % for all Ipo poles [nrows,ncolumns]=size(w); if nrows == 1 w = w.'; % if w is a row, make it a column end; if nIpo == 1 r(ii) = .1; else % check distances to other poles and zeroes pdiff = zp-po(ii)*ones_zp; % find the differences between % poles you are checking and other poles and zeros ipdiff = find(abs(pdiff)> tol); % ipdiff is all nonzero differences r(ii)=0.2*min(abs(pdiff(ipdiff))); % take half this difference r(ii)=min(r(ii),0.1); % take the minimum of this diff.and .1 end; t = linspace(-pi/2,pi/2,25); if (ii == originflag) t = linspace(0,pi/2,25); end; % gives us a vector of points around each Ipo s1 = po(ii)+r(ii)*(cos(t)+sqrt(-1)*sin(t)); % detour here s1 = s1.'; % make sure it is a column % Now here I reconstitute s - complex frequency - and % evaluate again. bottomvalue = po(ii)-sqrt(-1)*r(ii); part if (ii == originflag) % if this is an origin point bottomvalue = 0; end; topvalue = po(ii)+sqrt(-1)*r(ii); % the top value where detour stops nbegin = find(imag(w) < imag(bottomvalue)); % nnbegin = length(nbegin); % find all the points less than encirclement if (nnbegin == 0)& (ii ~= originflag) % around jw root sbegin = 0; else sbegin = w(nbegin); end; nend = find(imag(w) > imag(topvalue)); % find all points greater than nnend = length(nend); % encirclement around jw root if (nnend == 0) send = 0; % take magnitude of imag

else send = w(nend); end w = [sbegin; s1; send]; end else

% reconstituted half of jw axis

w = sqrt(-1)*w; end %end % this ends the loop for imaginary axis poles % ************************************************************* % back to the regular nyquist program here % Compute frequency response if (nargin1==1)|(nargin1==2)|(nargin1==3) gt = freqresp(num,den,w); else gt = freqresp(a,b,c,d,iu,w); end % *********************************************************** % % % % nw = length(gt); mag = abs(gt); % scaling factor added ang = angle(gt); mag = log2(mag+1); % scale by log2(mag) throughout

% for n = 1:nw % h(n,1) = mag(n,1)*(cos(ang(n,1))+sqrt(1)*sin(ang(n,1))); % end; % recalculate G(jw) with scaling factor % gt = h; % *********************************************************** ret=real(gt); imt=imag(gt); % If no left hand arguments then plot graph. if nargout==0, status = ishold; plot(ret,imt,'r-',ret,-imt,'g--') % plot(real(w),imag(w)) set(gca, 'YLimMode', 'auto') limits = axis; % Set axis hold on because next plot command may rescale set(gca, 'YLimMode', 'auto') set(gca, 'XLimMode', 'manual') hold on % Make arrows for k=1:size(gt,2), g = gt(:,k); re = ret(:,k); im = imt(:,k); sx = limits(2) - limits(1); [sy,sample]=max(abs(2*im)); arrow=[-1;0;-1] + 0.75*sqrt(-1)*[1;0;-1]; sample=sample+(sample==1); reim=diag(g(sample,:)); d=diag(g(sample+1,:)-g(sample-1,:)); % Rotate arrow taking into account scaling factors sx and sy d = real(d)*sy + sqrt(-1)*imag(d)*sx;

rot=d./abs(d); % Use this when arrow is not horizontal arrow = ones(3,1)*rot'.*arrow; scalex = (max(real(arrow)) - min(real(arrow)))*sx/50; scaley = (max(imag(arrow)) - min(imag(arrow)))*sy/50; arrow = real(arrow)*scalex + sqrt(-1)*imag(arrow)*scaley; xy =ones(3,1)*reim' + arrow; xy2=ones(3,1)*reim' - arrow; [m,n]=size(g); hold on plot(real(xy),-imag(xy),'r-',real(xy2),imag(xy2),'g-') end xlabel('Real Axis'), ylabel('Imag Axis') limits = axis; % Make cross at s = -1 + j0, i.e the -1 point if limits(2) >= -1.5 & limits(1) <= -0.5 % Only plot if -1 point is not far out. line1 = (limits(2)-limits(1))/50; line2 = (limits(4)-limits(3))/50; plot([-1+line1, -1-line1], [0,0], 'w-', [-1, -1], [line2, line2], 'w-') end % Axis plot([limits(1:2);0,0]',[0,0;limits(3:4)]','w:'); plot(-1,0,'+k'); if ~status, hold off, end % Return hold to previous status return % Suppress output end %reout = ret; % plot(real(p),imag(p),'x',real(z),imag(z),'o');

Converting Between System Representations


System variable representations State space to transfer function [ Zeros at infinity ] Transfer function to state space State space to zero/pole and transfer function to zero/pole Pole/zero to state space and pole/zero to transfer function A dynamic system is most commonly described in one of three ways: by a set of state-space equations and the corresponding matrices, by a transfer function with the numerator and denominator polynomials, or by a list of poles and zeros and the associated gain. From time to time, it is useful to convert between these various representations. MATLAB can do these conversions quickly and easily. In addition, beginning with version 5.0, M ATLAB has the ability to represent systems in a generic sense in a system variable. System variab are used independently of the original system notation, and it is easy to both store a system variable from any representation and to extract any of the three system representations from a system variable.

System variable conversions


Suppose you have a transfer function of the form
G(s) = 2s + 1 ------------4s^2 + 3s + 2

This can be represented in state space form with the following commands:
num=[2 1] den=[4 3 2]

This state space representation can be stored as a system variable with the command
G=tf(num,den)

which returns the following output to show what system was entered.
Transfer function: 2 s + 1 --------------4 s^2 + 3 s + 2

A state-space model can be extracted from the system variable G with the following command:
[A,B,C,D]=ssdata(G)

which returns the following state-space representation


A = -0.7500 1.0000 B = 1 0 C = 0.5000 D = 0 0.2500 -0.5000 0

This state-space representation can be stored in another (equivalent) system variable, H, with the following command
H=ss(A,B,C,D)

which returns the following output showing the relationships between the state, input, and output variab
a = x1 x2 b = x1 x2 c = y1 d = y1 Continuous-time system. u1 0 x1 0.50000 x2 0.25000 u1 1.00000 0 x1 -0.75000 1.00000 x2 -0.50000 0

To extract a zero-pole-gain model from this system variable, you enter the following command
[z,p,k]=zpkdata(H,'v')

The 'v' causes the function to return a vectorized version of the zeros and poles, which is useful for SISO systems. This function returns the following zero-pole-gain representation
z = -0.5000 p = -0.3750+ 0.5995i -0.3750- 0.5995i k = 0.5000

We can now form another system variable, K, from this zpk representation with the following command
K=zpk(z,p,k)

This command returns the following system


Zero/pole/gain: 0.5 (s+0.5) ------------------(s^2 + 0.75s + 0.5)

Finally, given this system variable, we can extract a transfer function representation with the following command
[num,den]=tfdata(K,'v')

(Again, the 'v' is useful for SISO systems.) This returns the following transfer function representation which is equal to the original transfer function before all the conversions (although both the numerator and denominator are scaled by a factor of 4)
num = 0 den = 1.0000 0.5000 0.7500 0.2500 0.5000

State space to transfer function:


In addition to using system variab to convert between representations, you can convert between representations directly. Suppose you have a set of state-space equations and you would like to convert them to the equivalent transfer function. This is done using the command

[num,den] = ss2tf(A,B,C,D,iu)

This command creates the numerator and denominator of the transfer function for the iu'th input. Note that in most of the systems considered in this tutorial, there is only one input and therefore the "iu" term does not need to be included. For example, suppose you had the following set of state equations:

If you want to change this to a transfer function, just run the following m-file:
A = [0 0 1 -0.05];

B = [0; 0.001]; C = [0 D = 0; [num,den]=ss2tf(A,B,C,D) 1];

MATLAB should return the following to the command window:


num = 0 0.0010 0

den = 1.0000 0.0500 0

This is the way MATLAB presents


0.001s + 0 -----------------s^2 + 0.05s + 0

You now have the transfer function that describes the system. As you can see this command is pretty easy to use. Here are some notes about ss2tf:

The numerator, num, will have as many rows as there are outputs (or rows in the matrix C). The numerator and denominator are returned in descending powers of s Care must be taken to check the numerator and denominator, as zeros at infinity may produce erroneous transfer functions.

Zeros at infinity
This last point needs some further explanation. We say that a system has zeros at infinity if the limit as s->infinity of the value of the transfer function is equal to zero; this happens whenever you have more poles than zeros. You will see this in the root locus plot as asymptotes which go to infinity (the number of asymptotes is equal to the number of zeros at infinity). MATLAB sometimes computes these zeros at infinity as being large finite numbers.When this happens, some of the coefficients in the numerator that are supposed to be zero end up being very small numbers. It may not seem like a big deal, but it can cause errors when trying to use the transfer function later on. You should always check your transfer function, and if numbers that are 0.0000 show up that are supposed to be zero, rewrite the numerator into MATLAB to compensate. A good example of this is given by the following set of state equations:

If you enter this into MATLAB using the following m-file:


A = [0 1 0 0 -0.1818 2.6727 0 0 0 0 -4.545 31.1818 B = [0 1.8182 0 4.5455]; 0 0 1 0];

C = [1 0 0 0 0 0 1 0]; D = [0 0]; [num,den]=ss2tf(A,B,C,D)

You should get the following transfer function:


num = 0 0 den = 1.0000 0.1818 -31.1818 -4.4541 0 0.0000 0.0000 1.8182 4.5455 -0.0000 0.0000 -44.5460 0

If you look at the numerator, the first and last element of each row are 0, while the second and fourth element in each row are 0.0000. If you look closer at each of these elements, you will find that they are not zero, but in fact some very small number. To see this, enter any of the following commands into the MATLAB command window: num(1,2), num(1,4), num(2,2) or num(2,4). You should get something similar to the following as an answer: 7.1054e-15, 6.2172e-15, 1.2434e-14, or 4.4409e-15. Look at the roots of the numerator polynomials using roots(num(1,:)) and you will see the roots of the numerator which are almost at infinity but not quite. This numerical inconsistency can be eliminated by adding the following line after the ss2tf command to get rid of the numbers that are not supposed to be there:
num = [num(1,3) 0 num(1,5) num(2,3) 0 num(2,5)];

Now all of the small numbers have been replaced with zeros. Always make sure to look at your transfer function and understand what it means before you use it in the design process.

Transfer function to state space:


The reverse of the command ss2tf is the tf2ss command, which converts a transfer function of a system into state-space form. The command is issued like this:
[A,B,C,D] = tf2ss(num,den)

One important fact to note is that although there is only one transfer function that describes a system, you can have multiple state-space equations that

describe a system. The tf2ss command returns the state-space matrices in control canonical form. Therefore, if you take a set of state-space equations, convert them into a transfer function, and then convert it back, you will not have the same set of state-space equations you started with unless you started with matrices in control canonical form. As an example, take the numerator and denominator created above and convert it back to state-space. This can be done with the following MATLAB code:
[A,B,C,D] = tf2ss(num,den)

MATLAB should output the following set of matrices:


A = -0.1818 1.0000 0 0 B = 1 0 0 0 C = 0 0 D= 0 0 1.8182 4.5455 0 0 -44.5460 0 31.1818 0 1.0000 0 4.4541 0 0 1.0000 0 0 0 0

This is obviously not the same set of matrices that were initially used, but the input-output behavior of this system is the same as that of the previous one. There are infinitely many ways to represent a given transfer function in statespace form; MATLAB chooses the control canonical form. The states will not have the same meaning as they originally did.

State space to zero/pole and transfer function to zero/pole:


There is also a third way to represent a dynamic system, and that is the polezero model. This model is basically the same as the transfer function model, except that the polynomials have been factored so the poles are all in the denominator and the zeros are in the numerator. The basic format looks like the following:

Remember that for a proper transfer function, the number of poles n is greater than or equal to the number of zeros m. MATLAB can make the transformations from either state-space or transfer function to the pole-zero representation. The commands to get the system into zero-pole form are:
[z,p,k] = tf2zp(num,den)

if you have a transfer function, and:


[z,p,k] = ss2zp(A,B,C,D,iu)

if you have a state-space model. Both of these commands should return three variab: z, p, k. The variable z returns all of the zeros in columns. There should be one column for every row in the transfer function numerator or every output, y (rows in the C matrix). The variable p returns all of the poles in a column. The variable k returns a column of gain values. The column should have as many rows as numerator rows or outputs, y. For example, using t he state space model and transfer function above, enter either of the following m-files:
num = [1.8182 4.5455 0 -7.4373 -44.5460; 0];

den = [1 0.1818 -31.1818 6.4786 0]; [z,p,k] = tf2zp(num,den)

or
A = [0 0 0 0 1 -0.1818 0 -4.545 0 2.6727 0 31.1818 0 0 1 0];

B = [0 1.8182 0 4.5455]; C = [1 0 0 0 0 0 1 0]; D = [0 0]; [z,p,k]=ss2zp(A,B,C,D,1)

and you should get the following output:

z = 4.9498 -4.9498 p = 0 0.2083 -5.7753 5.3851 k = 1.8182 4.5455 1.6362 0

There are two columns of zeros, and therefore the k matrix has two rows (one for each z column).

Pole/zero to state space and pole/zero to transfer function


As you may have already guessed, if you have a system described by the polezero method, you can convert that to either the state-space model or the transfer function. To get the state-space model, enter the following command:
[A,B,C,D] = zp2ss(z,p,k)

Again, it is important to note that more than one set of state-space matrices can describe a system. The state-space matrices returned from this command are also in control canonical form. For example, take the z, p, and k matrices you just created and convert them back to state-space:
[A,B,C,D] = zp2ss(z,p,k)

You should get the following state-space matrices:


A = -0.1818 1.0000 0 0 1 0 0 0 0 0 0 0 1.8182 4.5455 0 -7.4373 -44.5460 0 31.1818 0 1.0000 0 -6.4786 0 0 1.0000 0 0 0 0

B =

C = D =

You will recognize this as the same set of matrices you got using the command, tf2ss. To get a system described by a pole-zero model into a transfer function model, use the following command:
[num,den] = zp2tf(z,p,k)

Converting the same pole-zero model from above, you should get the following transfer function:
num = den = 0 0 1.0000 0 0 1.8182 4.5455 0 -7.4373 -44.5460 0 0

0.1818

-31.1818

6.4786

You will recognize this as the same transfer function we started out with.

Vous aimerez peut-être aussi