You are on page 1of 29

Matlab Basics Tutorial

Vectors
Functions
Plotting
Polynomials
Matrices
Printing
Using M-fles in Matlab
Getting help in Matlab
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 diferent toolboxes
available which extend the basic functions of
Matlab into diferent application areas; in
these tutorials, we will make extensive use of
the ontrol !ystems Toolbox. Matlab is
supported on "nix, Macintosh, and #indows
environments; a student version of Matlab is
available for personal computers. $or 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, lie a
vector. !nter each element of the vector "separated by a
space# between bracets, and set it e$ual to a variable.
%or example, to create the vector a, enter into the
Matlab command window "you can &copy& and &paste& from
your browser into Matlab to mae it easy#'
a ( )* + , - . / 0 1 23
Matlab should return'
a (
* + , - . / 0 1 2
Let's say you want to create a vector with elements
between 4 and +4 evenly spaced in increments of + "this
method is fre$uently used to create a time vector#'
t ( 4'+'+4
t (
4 + - / 1 *4 *+ *- */ *1 +4
Manipulating vectors is almost as easy as creating them.
%irst, suppose you would lie to add + to each of the
elements in vector 'a'. The e$uation for that loos lie'
b ( a 5 +
b (
, - . / 2 1 ** *4 0
6ow suppose, you would lie to add two vectors together.
7f the two vectors are the same length, it is easy. 8imply
add the two as shown below'
c ( a 5 b
c (
- / 1 *4 *+ *- +4 *1 */
8ubtraction of vectors of the same length wors exactly
the same way.
Functions
To mae life easier, Matlab includes many standard
functions. !ach function is a bloc of code that
accomplishes a specific tas. Matlab contains all of the
standard functions such as sin, cos, log, exp, s$rt, as well
as many others. 9ommonly used constants such as pi, and i
or : for the s$uare root of -*, are also incorporated into
Matlab.
sin"pi;-#
ans (
4.242*

To determine the usage of any function, type help
)function name3 at the Matlab command window.
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#$%$.&'%(;
y # sint";
plott)y"
*he plot contains appro+imately one period of a sine
wave. ,asic plotting is very easy in Matlab) and the
plot command has e+tensive 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.
*o 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%
*o enter this into Matlab) .ust enter it as a vector in
the following manner
+ # /0 1 -0' -& 23
+ #
0 1 -0' -& 2
Matlab can interpret a vector of length n40 as an nth
order polynomial. *hus) if your polynomial is missing
any coefficients) you must enter 5eros in the
appropriate place in the vector. For e+ample)
would be represented in Matlab as%
y # /0 $ $ $ 03
6ou can find the value of a polynomial using the
polyval function. For e+ample) to find the value of the
above polynomial at s#&)
5 # polyval/0 $ $ $ 03)&"
5 #
0(
6ou can also e+tract the roots of a polynomial. *his is
useful when you have a high-order polynomial such as
Finding the roots would be as easy as entering the
following command;
roots/0 1 -0' -& 23"
ans #
-'.'(7'
&.'819
-$.(2'0
$.(89$
:et!s say you want to multiply two polynomials
together. *he product of two polynomials is found by
taking the convolution of their coefficients. Matlab!s
function conv that will do this for you.
+ # /0 &3;
y # /0 7 83;
5 # conv+)y"
5 #
0 9 09 09
;ividing two polynomials is .ust as easy. *he deconv
function will return the remainder as well as the
result. :et!s divide 5 by y and see if we get +.
/++) <3 # deconv5)y"
++ #
0 &
< #
$ $ $ $
=s you can see) this is .ust the polynomial>vector +
from before. If y had not gone into 5 evenly) the
remainder vector would have been something other
than 5ero.
If you want to add two polynomials together which
have the same order) a simple 5#+4y will work the
vectors + and y must have the same length". In the
general case) the user-defined function) polyadd can
be used. *o use polyadd) copy the function into an m-
file) and then use it .ust as you would any other
function in the Matlab toolbo+. =ssuming you had the
polyadd function stored as a m-file) and you wanted
to add the two uneven polynomials) + and y) you could
accomplish this by entering the command%
5 # polyadd+)y"
+ #
0 &
y #
0 7 8
5 #
0 ' 0$
Matrices
?ntering matrices into Matlab is the same as entering
a vector) e+cept each row of elements is separated
by a semicolon ;" or a return%
, # /0 & 1 7;' 9 ( 8;2 0$ 00 0&3
, #
0 & 1 7
' 9 ( 8
2 0$ 00 0&
, # / 0 & 1 7
' 9 ( 8
2 0$ 00 0&3
, #
0 & 1 7
' 9 ( 8
2 0$ 00 0&
Matrices in Matlab can be manipulated in many ways.
For one) you can find the transpose of a matri+ using
the apostrophe key%
@ # ,!
@ #
0 ' 2
& 9 0$
1 ( 00
7 8 0&
It should be noted that if @ had been comple+) the
apostrophe would have actually given the comple+
con.ugate transpose. *o get the transpose) use .! the
two commands are the same if the mati+ is not
comple+".
Aow you can multiply the two matrices , and @
together. <emember that order matters when
multiplying matrices.
; # , B @
; #
1$ ($ 00$
($ 0(7 &(8
00$ &(8 779
; # @ B ,
; #
0$( 0&& 01( 0'&
0&& 07$ 0'8 0(9
01( 0'8 0(2 &$$
0'& 0(9 &$$ &&7
=nother option for matri+ manipulation is that you can
multiply the corresponding elements of two matrices
using the .B operator the matrices must be the same
si5e to do this".
? # /0 &;1 73
F # /& 1;7 '3
C # ? .B F
? #
0 &
1 7
F #
& 1
7 '
C #
& 9
0& &$
If you have a sDuare matri+) like ?) you can also
multiply it by itself as many times as you like by
raising it to a given power.
?E1
ans #
1( '7
80 008
If wanted to cube each element in the matri+) .ust
use the element-by-element cubing.
?.E1
ans #
0 8
&( 97
6ou can also find the inverse of a matri+%
F # inv?"
F #
-&.$$$$ 0.$$$$
0.'$$$ -$.'$$$
or its eigenvalues%
eig?"
ans #
-$.1(&1
'.1(&1
*here is even a function to find the coefficients of
the characteristic polynomial of a matri+. *he GpolyG
function creates a vector that includes the
coefficients of the characteristic polynomial.
p # poly?"
p #
0.$$$$ -'.$$$$ -&.$$$$
<emember that the eigenvalues of a matri+ are the
same as the roots of its characteristic polynomial%
rootsp"
ans #
'.1(&1
-$.1(&1
Printing
Printing in Matlab is pretty easy. Hust follow the
steps illustrated below%
Macintosh
*o print a plot or a m-file from a Macintosh)
.ust click on the plot or m-file) select Print under
the File menu) and hit return.
Iindows
*o print a plot or a m-file from a computer
running Iindows) .ust selct Print from the File
menu in the window of the plot or m-file) and hit
return.
Jni+
*o print a plot on a Jni+ workstation enter the
command%
print -PKprinternameL
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 Glpr -P plot.psG If you are using a MP
workstation to print) you would instead use the
command Glpr -d plot.psG
*o print a m-file) .ust print it the way you would
any other file) using the command Glpr -P Kname
of m-fileL.mG If you are using a MP workstation
to print) you would instead use the command Glpr
-d plot.psKname of m-fileL.mG
Jsing M-files in Matlab
*here are slightly different things you need to know
for each platform.
Macintosh
*here is a built-in editor for m-files; choose
GAew M-fileG from the File menu. 6ou can also
use any other editor you like but be sure to save
the files in te+t format and load them when you
start Matlab".
Iindows
<unning Matlab from Iindows is very similar to
running it on a Macintosh. Mowever) you need to
know that your m-file will be saved in the
clipboard. *herefore) you must make sure that it
is saved as filename.m
Jni+
6ou will need to run an editor separately from
Matlab. *he best strategy is to make a directory
for all your m-files) then cd to that directory
before running both Matlab and the editor. *o
start Matlab from your Fterm window) simply
type% matlab.
6ou can either type commands directly into matlab) or
put all of the commands that you will need together in
an m-file) and .ust 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.
Cetting help in Matlab
Matlab has a fairly good on-line help; type
help command name
for more information on any given command. 6ou 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
e+ample page.
Mere are a few notes to end this tutorial.
6ou can get the value of a particular variable at any
time by typing its name.
,
, #
0 & 1
7 ' 9
( 8 2
6ou can also have more that one statement on a single
line) so long as you separate them with either a
semicolon or comma.
=lso) 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 GansG.
Jser feedback
Ie would like to hear about difficulties you had with
the tutorials) suggestions you have for improvement)
errors that you found) or any other comments that
you have. *his feedback is anonymous; include your
email address if you want a reply.

Some Jseful M=*:=, @ommands
First) the most important command in M=*:=,%
LL help commandNname ;isplays complete
information about any
command. *ake note
of any cross
references at the
end of each help
entry. help with no
command specified
lists all categories of
available commands.
Aote% helpwin brings
up a separate gui
help window -- useful
if you!re doing other
things in the main
window.
Interacting with M=*:=,%
LL command
LL command;
= semicolon after any
command suppresses
output from that
command to the
M=*:=, window but
not) for e+ample) to
a figure" - especially
useful if the output
is a very long vector.
LL KJP =<<OIL <ecalls the last
command entered.
6ou can repeat it to
go farther back) or
press K;OIA
=<<OIL to scroll
forward.
LL abcKJP =<<OIL <ecalls the last
command entered
that starts with
GabcG.
LL more on
LL more off
*urns on and off
more) which displays
all output including
help information" one
screen at a time.
LL who *ells you what
variables currently
e+ist.
LL clear
LL clear variable
;eletes all variables)
or the specified
variable.
LL format long g
LL format compact
;isplays variables
but not systems"
with more digits.
;oes not affect
storage or
computation.
Cets rid of the e+tra
blank lines in the
display.
@ommands for making and formatting plots%
LL p0#plott0)y0";
LL deletep0"
Plots y0 vs. t0. Aote
that setting the plot
eDual to a name lets
you delete it
afterwards - useful
if you!re plotting
several things in the
same figure and make
a mistake. y0 and t0
must be vectors of
the same si5e.
LL ploty%)0")y%)&"" Plots the second
column of matri+ y
vs. the first column.
See note at end of
section.
LL subplotm)n)p" ,reaks the figure up
into m+n separate
graphs) and selects
the p
th
one as
current; if there are
already m+n graphs)
leaves graphs as they
are and selects the
p
th
one.
LL +label!labelNte+t!"
LL ylabel!labelNte+t!"
LL title!titleNte+t!"
:abels the a+es or
the entire subplot
with specified te+t
note single Duotes".
LL g0 # gte+t!plotNte+t!";
LL deleteg0"
:ets you place the
given te+t in single
Duotes" by clicking on
the graph. Aote that
setting the gte+t
eDual to a name lets
you delete it
afterwards.
LL grid *oggles on and off a
grid superimposed
over the current
graph; you can also
type grid on and grid
off.
LL sgrid ;raws a grid on a
plot of the s plane
root locus plot or
pole and 5ero
locations") which
consists of lines of
constant damping
coefficient 5eta" and
natural freDuency
wn".
LL hold *oggles on and off
the plot hold) which
adds new plots to any
already in the graph
without it) new plots
delete previous ones".
6ou can also type
hold on and hold off.
LL a+is/+min +ma+ ymin
yma+3"
LL a+is auto
Sets the limits of
the + and y a+es
manually) or lets
them be set
automatically. *here
are also many other
options available for
a+is.
LL 5oom :ets you select an
area of the plot
using the mouse" to
5oom in on. =lso)
clicking the left
mouse button once
will 5oom in) and
clicking the right
button will 5oom out)
by a factor of two.
;ouble clicking the
right mouse button
returns to the
original scale; typing
5oom again turns off
the 5oom function.
LL /+) y3 # ginputn" :ets you input the
LL /+) y3 # ginput coordinates of points
on the graph with the
mouse; collects n
points and stores
them in the vectors +
and y) or if n is
absent) keeps
collecting points until
you press K?A*?<L.
Matri+ and vector manipulation commands%
LL k#linspacek0)k&"
LL k#linspacek0)k&)n"
<eturns a vector of
0$$ or) if specified)
n" points eDually
spaced between +0
and +&.
LL ma+y" <eturns the largest
element in the vector
y.
LL inv=" <eturns the inverse
of the sDuare)
nonsingular matri+ =.
LL det=" @alculates the
determinant of the
matri+ =.
LL eig="
LL /V);3 # eig="
<eturns the
eigenvalues of =) or
sets V to a matri+
containing the
eigenvectors of = and
sets ; to a diagonal
matri+ containing the
corresponding
eigenvalues.
LL rank=" <eturns the rank of
any matri+ =.
@ommands useful in system analysis%
LL rootsf" <eturns the roots of
a polynomial) where f
is a vector containing
the coefficients of
the polynomial.
LL convP0)P&" Multiplies two
polynomials P0 and
P& are vectors
containing the
coeffiecients of the
polynomials" and
returns the resulting
coefficients. *his is
actually a convolution
of the two vectors)
which also works as
coefficient
multiplication.
LL sys0#tfnum)den"
LL sys&#ss=),)@);"
LL sys0#tfsys&"
LL sys&#sssys0"
@reates a system) as
a transfer function
or state-space
representation. =lso
converts between two
different
representations of a
system. *he 5pk
5ero>pole>gain"
command works
similarly.
LL /<)P)P3#residuenum)den" Finds the partial
fraction e+pansion of
a function Ms")
where num is a
vector containing the
coefficients of the
numerator) and den
of the denominator)
of Ms". <eturns the
numerators <" and
poles P" of the
partial fractions and
the remaining
polynomial P"%
Ms" # <
0
>s-P
0
" 4 <
&
>
s-P
&
" 4 ... 4 <
n
>s-
P
n
" 4 Ps".
LL sys1#seriessys0)sys&" Finds the result of
putting Systems 0
and & in series) and
returns either the
resulting transfer
function numerator
and denominator or
the resulting state
space matrices.
Mi+ing system
descriptions will
work.
LL sys1#feedbacksys0)sys&"
LL
sys&#feedbacksys0)tf0)0""
Finds the result of
adding System & as a
feedback loop to
System 0) assuming a
negative feedback)
and returns either
the resulting transfer
function numerator
and denominator or
the resulting state
space matrices.
LL impulsesys"
LL stepsys"
Plots the impulse
response or step
response of the given
system. Jseful trick%
if you have a :aplace
transform Fs" of a
time function ft")
plotting the impulse
response of Fs" is
the same as plotting
ft".
LL /y)t)+3#impulsesys"
LL /y)t)+3#stepsys"
Civing impusle and
step output variables
returns the output
y") time t") and
states+" if state
space" vectors) which
you can then plot or
manipulate.
LL initialsys)+$" Plots the behavior of
the given state-space
system with initial
condition +$ and no
input.
LL lsimsys)u)t)+$" Plots the response of
the given system to
the input signal ut".
*he initial condition
+$ can be added for
state-space systems.
LL bodesys0)sys&)..."
LL
/mag.phase)w3#bodesys)w"
LL nyDuistsys"
LL Qre)im)w3#nyDuistsys)w"
Plots the ,ode or
AyDuist diagram for
the given systems".
= plot is drawn if no
return arguments.
*he freDuency points
may be specified in
the vector w .
LL marginsys"
LL
/gm)pm)wcg)wcp3#marginsys"
Finds the gain margin
and phase margin)
and the freDuencies
at which they occur)
of the given system.
If run with no output
arguments) margin
also displays the
,ode plot) with the
margins marked on it
and their values
displayed in the
figure title.
LL rlocussys)k" Plots the root locus
for the given system)
i.e. where dens" 4
kBnums" # $ or
eDuivalent for the
state space form".
*he vector of values
for k is optional.
LL rlocfindsys"
LL /k)poles3#rlocfindsys"
:ets you select a pole
location from a root
locus plot using the
mouse) and returns
the value of k needed
to give such a pole)
as well as all the
resulting pole
locations in the
vector poles if
present". rlocfind
picks the point on the
locus closest to the
crosshairs; note that
you must already
have the root locus
graphed to be able to
see points you might
want to pick.
LL sys&#canonsys0)!form!" Finds a canonical
form of the given
system; the argument
GformG can be either
GmodalG or
GcompanionG in single
Duotes".
LL rltool
Opens a tool for
designing controllers
using the root locus
plots.