(
Ye 2
Gr)
cy 7) 2 1 -
(N52) ge soe (211, 2)
legie
n
Control
Tutorials for
Matlab
Matlab Basics Tutorial
Key Matlab Commands used in this tutorial are: plot polyval roots conv decor
inv eig poly
Note: Non-standard Matlab commands used in this tutorials are highlighted in green.
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 Matlab command window (you can "copy" and "paste”
from your browser into Matlab to make it easy):
a= (123456987)
‘Matlab should return:
Aa
123456987
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
0 2 4 6 6 10 12 14 16 18 20Manipulating 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
34567611 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=atb
46 6 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. Matlab 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 nelp [function name] at the Matlab
command window.
Matlab even allows you to write your own functions with the £u 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)‘Sing wave a8 tncion of fe
1
os} /
os /
oat
o2}/
o
02!
oa)
on) \
08 \
° \
o + 2 8 4 6 6 7 8
The plot contains approximately one period of a sine wave. Basic plotting is very easy in
Matlab, and the pict command has extensive add-on capabilities, I would recommend you
visit the plotting page to learn more about it.
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:
544359 1552-2549
To enter this into Matlab, just enter it as a vector in the following manner
x= 23-15-29)
13-158 -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,
s4e1
would be represented in Matlab as:
y= 0002)
You can find the value of a polynomial using the polyvai function. For example, to find
the value of the above polynomial at
z= polyval({1 0 0 0 11,2)
7
You can also extract the roots of a polynomial. This is useful when you have a high-order
polynomial such as544.353 1552-2549
Finding the roots would be as easy as entering the following command;
roots({1 3 -15 -2 9])
5745
+5836
27952
- 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. Matlab’s function cony that will do
this for you.
x= [1 21
y= 48);
2 = conv(x,¥)
16 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 =
12
R=
0000
‘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.
If you want to add two polynomials together which have the same order, a simple 2=x+y
will work (the vectors x and y must have the same length), In the general case, the user-
defined function, can be used. To use polyadd, copy the function into an m-file,
and then use it just as you would any other function in the Matlab toolbox, Assuming you
had the polyadd function stored as a m-file, and you wanted to add the two uneven
polynomials, x and y, you could accomplish this by entering the command:
z add (x, ¥)
12
re
148
fees) 10)Matrices
Entering matrices into Matlab is the same as entering a vector, except cach row of elements
is separated by a semicolon (;) or a return:
B= (12.3 4;5 67 679 10 11 121
Be
102 3 4
5 6 7 8B
peeetoee tig 12]
Bet1234
Seas
910 11 12]
Be
fea
ee nea 7a ee)
9 10 Wt 42
Matrices in Matlab can be manipulated in many ways. For one, you can find the transpose
of a matrix using the apostrophe key:
15 9
2 6 10
307 a
48 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 matix is not complex)
Now you can multiply the two matrices B and C together. Remember that order matters
when multiplying matrices.
30-70 «110
70 174 278
110° 278 446
107 122 137 152
122° 140 «158-176
137 158 179 200
152 176 200 224Another 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)
22
304
pe
23
405
Ge
2 6
12 20
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.
£3
ans ~
3784
a1 ue
If wanted to cube each element in the matrix, just use the element-by-element cubing.
*3
1 8
27 64
You can also find the inverse of a matrix:
x = inviz)
a
-2.0000 1.0000
115000 0.5000
or its eigenvalues:
eigie)
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)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)
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 m-file, select
Print under the File menu, and hit return.
Windows
To print a plot or a m-file from a computer running Windows, just selct 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
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 "Ipr -P plots" If you
are using a HP workstation to print, you would instead use the command "Ipr -d
plot.ps*
To print a m-file, just print it the way you would any other file, using the command
“Ipr -P .m" If you are using a HP workstation to print, you would
instead use the command "Ipr-d plot.ps.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 Matlab),
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.mUnix
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.
Getting help in Matlab
Matlab has a fairly good on-line help; type
help conmandnane
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=
10203
45 6
7 8 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”,
vine bole Introduction to Matlab Functions
‘When entering a command such as roots, plot, or step into matlab what you are really
doing is running an 4 ith inputs and outputs that has been written to accomplish a
specific task. These f 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 variables.
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 [outputi,output2] = filename (inputl, input2, input3)
A function can input or output as many variables as are needed. The next few lines contain
the text that will appear when the help filename command is evoked. These lines areoptional, but must be entered using 3 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) ) 7
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.n, might look like.
function [var3] = add (varl,var2)
Sadd is a function that adds two numbers
var3 = vari¢var2;
If you save these three lines in a file called "add.m" in the Matlab 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 Matlab software, for
more sophisticated examples, or try help function for more information.
Plotting in Matlab
One of the most important functions in Matlab is the piot function, piot 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:
ya3e
We could create a m-file with the following lines of code:
x = 0:0.1:100
y = 34x,
plot (x,y)
which will generate the following plot,309,
280)
200
150
100
50
2 4060-80 —‘t00
‘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. Matlab can plot a 1 x n veetor versus an ~
x 1 vector, or a I 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 pict 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:
1100;
y= 3¢x?
plot (xy, "r2")
The plot now looks like:
300
250
200
150
100
50
10‘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 yellow point
m magenta circle
cyan aeomark
r red plus
g green solid
b blue star
«white dotted
k black dashaot
dashed
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:
Linspace (0,2*pi, 50) 7
y= singos
2 = cos (x}7
plot (x, Ys'E"s X,2,"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
os:
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 (xy) 'E")
2 = cos(x)s
hold on
plot (x/2,'gx")
hold off
Always remember that if you use the no1d on command, all plots from then on will be
generated on one set of axes, without erasing the previous plot, until the noid off
command is issued,
iSubplotting
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 pth 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 = Linspace (0, 2*pi, 50) ;
y= sin(x);
2 = cos(x);
w= tan(x);
subplot (2,2,1)
r
50
0 Seueai0
As you can see, there are only three plots, even though I created a 2 x 2 matrix of 4
subplots, I 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. I could have easily made
another plot using the line 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 subpiot 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
mefile, it would be plotted in the third position in the subplot, erasing the tangent plot. To
12solve this problem, the figure should be cleared (using c1£), 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((unin, xmax, ymin, ymax))
For instance, suppose want to look at a plot of the function y~exp(5t}-I. If you enter the
following into Matlab
e=0:0.01:57
yrexp(5*t]
plot (t.y)
you should have the following plot:
x10” yeexp(styt
1
9)
o 4 2 3 4 5
As you can see, the plot goes to infinity. Looking at the y-axis (scale: 8¢10), 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:
B+0 yeexp(5t}-1, axis changed
40|
30
20
10
O33
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 hep 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 titie command), x-axis label (with the xiabe1 command), y-axis label
(with the yiabe1 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: x1abel (‘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, yoor, "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 step response 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("step response of something’)
xlabel('time (sec) ')
ylabel ('position, velocity, or something like that")
gtext (‘unnecessary labeling")
The text “unnecessary labeling” was placed right above the position, I clicked on. The plot
should look like the following:
4step response of something
innecessary labeling
postion, velocity, or something lke that
a)
a é
time (sec)
Other commands that can be used with the prot command are:
1s (clears the current plot, soit is blank)
figure (opens a new figure to plot on, so the previous figure is saved)
close (closes the current figure window)
1oglog (same as plot, except both axes are log base 10 scale)
semi logx (same as plot, except x-axis is log base 10 scale)
semi logy (same as plot, except y-axis is log base 10 scale)
grid (adds grid line to your plot)
Of course this is not a complete account of plotting with Matlab, but it should give you a
nice start,
15Function Polyadd:
adding two vectors of different lengths
Below is the function po1yada.m. This function will add two polynomials together even if
they do not have the same length. To use polyadd.m in Matlab, enter
(poly1, poly2). Copy the following text into a file polyadd.m, and put it in the
same directory as the Matlab software, or in a directory which is contained in Matlab’s
search path. The function itself was written by Justin Shriver of the University of Michigan,
function [polyi=polyadd ipolyl,poly2)
Scopyright 1996 Justin Shriver
Spolyadd(poly2,poly2) adds two polynominals possibly of uneven length
if length (poly1)0
poly=[zeros(1,mz),short]+long?
else
poly=long+short;
end
16