You are on page 1of 15

A PRIMER IN MATLAB

ME C91 Fundamentals of Control Systems I Winter, 1996 J.E. Colgate

Matlab is a very powerful application for performing all sorts of analyses on linear systems. For instance, Matlab can be used to solve for pole and zero locations, to solve for time responses (e.g., step responses) and frequency responses, to plot root loci, and much, much more. Our version of Matlab runs on Macintoshes, which are available in the ME Mac Cluster (3rd floor, ME wing). Copies of the User's Guides for Matlab, the Matlab Control Toolbox, and the Matlab Robust Control Toolbox are available in the room. These manuals should be used for really getting to know about what Matlab can do this primer is just to get you started, and is very incomplete. Matlab uses a standard Macintosh environment, with pull-down menus, dialog boxes, and assorted windows. There are four basic types of windows in Matlab: Command Window: with this window you can use Matlab in an interactive mode. The Matlab prompt, , appears in this window, allowing you to enter commands directly and see the results of computations immediately. Graphics Window: this window displays plots. The graphics capabilities in Matlab are quite good for the sort of plots that you would typically generate in C91. Edit Window: this is the window you would use for writing programs (Matlab has its own modest programming language including control features such as FOR loops and IF statements; programs are called "Scripts.") and functions (similar to programs, except that you can pass arguments to a function, and variables defined inside a function file are local to the function, whereas those defined inside a script are global; you might, for instance, write a function to compute step responses of linear systems, though Matlab already has one of these). Help Window: this is self-explanatory.

An important thing to understand about Matlab, is that the basic entity that it works with is a matrix. A vector is just a 1n or n1 matrix, and a scalar is just a 11 matrix.

Note: If Matlab is giving you errors that you shouldn't have and generally doing weird things, exit Matlab, go into the Matlab folder, find the file named "Matlab Settings," and trash it. Restart Matlab, and good luck.

Matlab Primer

1. Using the Command Window Suppose that you want to enter a 22 matrix, a, and a 21 vector, b, and take their product. You could do the following (try it):

a=[1,2;3,4] a= 1 3 b=[5;6] b= 5 6 c=a*b c= 17 39 2 4

this is what you enter to define a Matlab responds with this, indicating that a is a 22 matrix

As the example above indicates, "," is a row delimiter (separating elements that are in the same row), and ";" is a column delimiter. There are other ways to delimit:

a=[1 2; 3 4] a= 1 3 a = [1 2 3 4] a= 1 3 2 4 2 4

use spaces instead of commas

use a return instead of a semicolon

Matlab Primer

You can suppress Matlab's response by adding a semicolon at the end of the command line:

a=[1,2;3,4];

notice the semicolon ending the line Matlab doesn't respond, except to prompt you for another command

Now, suppose that you had entered the matrix a as above, only to realize that you really wanted to enter it as: a= 1 2 3 5 You could simply re-enter it, or you could change the one incorrect entry as follows:

a(2,2)=5 a= 1 3 2 5

read a(2,2) as a(row 2, column 2)

Or, suppose that you wanted to extract from a its first column and name it "d." This can be done as follows:

d=a(:,1) d= 1 3

The colon indicates that all rows should be included

Matlab provides a lot of other shortcuts for entering certain types of matrices. Suppose that you want to generate a vector of equally spaced points, perhaps for use as a sequence of points in time. It is easy:

t_row=[0:.1:1] t_row = Columns 1 through 7 0 0.6000 Columns 8 through 11 0.1000 0.2000 0.3000 0.4000 0.5000

Matlab Primer

0.7000

0.8000

0.9000

1.0000

A matrix can be transposed as follows:

t_column = t_row' t_column = 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
Some useful odds and ends:

e=eye(3) e= 1 0 0 0 1 0 0 0 1

f=ones(2,3) f= 1 1 1 1 1 1

Matlab remembers the latest versions of all the variables you have defined. If you want to find out what these are, you can ask "who?"

Matlab Primer

who Your variables are: a b c d e f t_column t_row

leaving 645696 bytes of memory free.


You can get rid of all of these with "clear."

clear who Your variables are:

leaving 652540 bytes of memory free.


Matlab also defines some variables of its own, including:

pi ans = 3.1416 i ans = 0 + 1.0000i


yes, complex numbers are o.k.

ans is a variable that is assigned any time that


you do not explicitly provide a name, such as pie=pi

But be careful, you can unwittingly redefine these variables:

pi=3 pi = 3
There's lots more that you might want to know about the command window, and you can find it in the Matlab User's Guide. But this is a start. Now let's do some graphics.

Matlab Primer

2. Graphics Window
Before you can use the graphics window, you have to have something to graph, so in the command window you might do the following:

x=[1:.1:10]; y=sin(x);
Then, to plot:

a vector of input values sin(vector) computes the sine of the vector component by component

plot(x,y)
And in the graphics window, you will see: 1

0.5

-0.5

-1 1 2 3 4 5 6 7 8 9 10

Labels and such can be added by using the the commands xlabel(x), ylabel(y) and title(myplot). If you print the graph directly by using "Print" from the "File" menu, it will look better than this, because Matlab will do some interpolation and smoothing. There are lots of other things you can do with Matlab's graphics routines, including changing line types, axis limits, etc. You also have several types of "graph paper" available, including semilog and loglog, which can be useful in plotting frequency responses. An example of using semilog paper would be:

semilogx(x,y)

Matlab Primer

Semilog Plot of Sin(x)

0.5

-0.5

-1 100 x

101

3. Using Matlab for Simulating Dynamic Systems


You can describe a linear dynamic system to Matlab in one of three ways: State Space Form state equations: output equations: x = Ax + Bu y = Cx + Du

you specify the matrices A, B, C, and D Transfer Function Form transfer function: Y(s) s m + m-1s m-1 + = C(sI - A) -1B + D = m U(s) ns n + n-1s n-1 + + 0 + 0

where n = number of zeros, n = number of poles = number of states you specify the vectors:

num = [m m-1 ... 0] den = [n n-1 ... 0]

Zero-Pole Form (little used) transfer function: Y(s) K(s-z1)( s-z2) (s-zm) = (s-p1)( s-p2) (s-pn) U(s)

where z1-zm are the zeros and p1-pn are the poles, and K = m/n.

Matlab Primer

you specify the scalar K, and the vectors:

z = [z1 z2 ... zm] p = [p1 p2 ... pn]

Matlab provides a set of functions for going from one form to another:

[num,den]=ss2tf(a,b,c,d,iu); iu specifies which input is to be [z,p,k]=ss2zp(a,b,c,d,iu); considered; typically there is only one [a,b,c,d]=tf2ss(num,den); input, and iu = 1 [z,p,k]=tf2zp(num,den); [a,b,c,d]=zp2ss(z,p,k); [num,den]=zp2ss(z,p,k);
Once you have specified a dynamic system, usually in state space or transfer function form, there are many things that you can do with it. You can use Matlab to solve for a time domain response, such as response to initial conditions, an impulse response, a step response, or a response to an arbitrary input. You can have Matlab solve for the roots of a numerator or denominator polynomial (zeros or poles) or for the eigenvalues of an A matrix (poles). Matlab can create a pole-zero plot. You can also use Matlab to plot frequency response (magnitude and phase Bode plots). Example A Second Order System Consider the linear, time-invariant, second-order system shown below: K

M B The transfer function from force to position is: x( s) 1 = F(s) Ms 2 + Bs + K

F(t)

x(t), v(t), p(t)

Suppose the the parameter values are known to be K=5, B=1, and M=1, and we would like to have Matlab compute and plot the response of the mass's position to a unit step in force. The transfer function can be entered into Matlab, and, assuming zero initial conditions, the step response calculated and plotted as follows:

num=1; den=[1 1 5]; t=0:.1:10;

numerator polynomial denominator polynomial vector of points in time, from 0 to 10 seconds, by tenths of a second

Matlab Primer

y=step(num,den,t);

plot(t,y)
On the graphics screen, you will see: 0.3 0.25 0.2 0.15 0.1 0.05 0 0 1 2 3

Response of output to unit step in input; output is a vector of response values corresponding to time values in t. step is a function supplied in the Control Toolbox; it takes as arguments the numerator and denominator vectors, and the time vector. plots y vs. t.

10

You can go on to add labels to this plot.

If you want to find the poles of this system, you can simply ask Matlab to find the roots of the denominator:

poles=roots(den) poles = -0.5000 + 2.1794i -0.5000 - 2.1794i


Now suppose that you are interested in the velocity, v(t). The appropriate transfer function is: v( s) s = 2+s+5 F(s) s

Matlab Primer

10

This transfer function obviously contains a zero at s=0, although Matlab could be used to solve for it. Matlab also makes nice pole-zero plots:

num=[1 0]; zeros=roots(num) zeros = 8.8818e-16 plot(real(poles),imag(poles),'x',... ellipsis indicates that command real(zeros),imag(zeros),'o') will be continued on next line. real takes real part, imag takes imaginary part, 'x' tells
Matlab to mark points with an x, and 'o' tells it mark points with an o. After adding a grid and labels to the plot, it looks like:

3 2 imaginary (rad/sec) 1 0 -1 -2 -3 -0.5

Pole-Zero Plot

-0.45

-0.4

-0.35

-0.3

-0.25

-0.2

-0.15

-0.1

-0.05

real (rad/sec)

This might be a good situation for doing some manual axis scaling by using "Axis Limits..." in the "Graph" pull-down menu, then re-issuing the plot command. For instance, the plot can be made to look like this:

Matlab Primer

11

Pole-Zero Plot 4 2 0 -2 -4 -3 -2.5 -2 -1.5 -1 real (rad/sec) -0.5 0 0.5 1

Matlab is also quite good at generating frequency response plots. Suppose that you want the magnitude and phase bode plots of the transfer function from force to position. You can generate these as follows:

num=1; w=logspace(-2,2,100); [mag,phase]=bode(num,den,w); mag=20*log10(mag); subplot(211), semilogx(w,mag) subplot(212), semilogx(w,phase)

imaginary (rad/sec)

position is output. generates a vector of 100 points evenly spaced on a logarithmic scale from 10-2 to 102. calculates frequency response converts magnitude values to decibels.

subplot(mnp) breaks the graph


window into an mn grid and uses the pth box for the subsequent plot.

The plots, fully labeled, look like:

Matlab Primer

12

0 Mag (dB) -50 -100 10-2

Magnitude Bode Plot

10-1

100 frequency (rad/sec)

101

102

0 Phase (deg) -100 -200 10-2

Phase Bode Plot

10-1

100 frequency (rad/sec)

101

102

4. Using the Edit Window


Suppose that you want to take the second order system considered above, and examine the effect of changing the damping coefficient, B, on the shape of the step response. You figure that looking at ten different values of B ought to do the job, but you don't really want to sit at the keyboard typing in the appropriate matrices for each individual case. Now is the time to use the Edit Window. Using the Edit Window, you can write a batch file (or, in Matlab parlance, a script file) to relieve you of the tedium. An example of a script file which will do this job is "dampeffect.m". To bring up the Edit Window, go to the "File" pull-down menu, and select "New M-File." Then type in the following, and "Save As..." as "dampeffect.m."

% dampeffect.m % % This script file will compute thirteen step responses for a % second order system with various values of the damping % coefficient, B. % The results will be plotted with "mesh." % clear; % clear all variables % B = 0:.5:6; % vector of values of B n = length(B); % number of values of B % num=1; % numerator

Matlab Primer

13

% t = 0:.1:10; % % Begin loop % for i=1:n den = [1 B(i) 5]; y(:,i) = step(num,den,t); end % mesh(y')
The plot will look like:

% time vector

% denominator % step response

Where the position axis runs straight up, the time axis runs up and to the right, and the damping coefficient axis runs down and to the right. With a little bit of work, you can probably make this look even better. Of course, there are other ways to display the data. You can get Matlab to plot individual step responses, and pause after each one, waiting for you to hit the return key, or waiting for some number of seconds to pass. Check pause in the User's Guide. In addition to creating script files, the Edit Window will let you create functions, which may be called from the command window, or by other script files. A function is just like a script file, except that: the first line must contain the word "function," arguments may be passed to a function, and the variables defined inside a function are local to it, and therefore invisible to the global workspace (they don't show up when you issue a "who." Matlab already has many functions defined; these are the things in the "Toolboxes." For

Matlab Primer

14

instance, step is a function which you could bring up to the Edit Window and alter (please, never, never, do this, lest you incur the wrath of myself and your classmates). step looks like this:

function [y,x] = step(a,b,c,d,iu,t) %STEP Step response of continuous-time linear systems. % Y = STEP(A,B,C,D,iu,T) calculates the response of the system: % . % x = Ax + Bu % y = Cx + Du % % to a step applied to the iu'th input. Vector T must be a % regularly spaced time vector that specifies the time axis % for the step response. STEP returns a matrix Y with as % many columns as there are outputs y, and with LENGTH(T) % rows. [Y,X] = STEP(A,B,C,D,iu,T) also returns the state % time history. % % Y = STEP(NUM,DEN,T) calculates the step response from the % transfer function description G(s) = NUM(s)/DEN(s) where % NUM and DEN contain the polynomial coefficients in % descending powers. % % J.N. Little 4-21-85 Copyright (c) 1985, 1986 by the MathWorks, Inc.

nargs = nargin; if (nargs == 3) % Convert to state space t = c; iu = 1; [a,b,c,d] = tf2ss(a,b); nargs = 6; end error(nargchk(6,6,nargs)); error(abcdchk(a,b,c,d)); % The state space model of an integrator is % a1=0; b1=1; c1=1; d1=0; % Remove all inputs except input iu and put % integrator in series with a,b,c,d: [a2,b2,c2,d2] = series(0,1,1,0,a,b(:,iu),c,d(:,iu)); [y,x] = impulse(a2,b2,c2,0,1,t);

Matlab Primer

15

% remove the integrator state sa = size(a2); x = x(:,2:sa(1));

You might also like