MATLAB Basics and Tutorial Guide
MATLAB Basics and Tutorial Guide
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.
Types
Fundamentally there is one type, a rectangular array of numbers. There are no type
declarations. The dimensions of an array are determined by the context. Nevertheless,
it is convenient to think of three types in the language:
Names
Names consist of a letter followed by zero or more letters, digits, and underscore
characters. Uppercase and lowercase letters are distinguished; thus, A1 and a1 denote
different variables.
Scalar constants
These values are written with an optional decimal point and an optional power of 10.
A minus sign is placed at the front of negative values. No blanks are permitted within
a value.
Examples of legal values are:
2
99 39.24 -0.0075 1.35e-24 0.2E-5 12.0e44
Display Format
The value of variables may be displayed in several ways, including short, long, short e
and long [Link] default format is called a short format and shows the number to 4
decimal places. For instance, if you type :
x = 32.75
MATLAB responds with
x =
32.7500
Should you specify that you wish to use the short display format at this
format, MATLAB displays x in the same manner.
Eg.
format short
x
x =
32.7500
The long format has fourteen decimal places.
Eg.
format long
x
x =
32.75000000000000
z
z =
2.00000000000000 - 5.00000000000000i
The two e formats give values in scientific form (i.e., floating-point), both
long and short:
format short e
x
x =
3.2750e+01
format long e
x
x =
3.275000000000000e+01
3
Arithmetic operators
D =
0.2500 0.4000
0.5000 0.7143
4
precedence than relational operations which, in turn, are lower in precedence than
arithmetic operations.
Vectors
To start off, we will create 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 here into Matlab to make it easy):
a = [1 2 3 4 5 6 9 8 7]
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. 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)
5
ans =
0.7071
To determine the usage of any function, type help [function name] at the
Matlab command window.
Matlab even allows you to write your own functions with the function command.
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)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
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. I would
recommend you read the plotting page to learn more about it (At the end of this
document.)
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:
6
s 4 + 3s 3 − 15s 2 − 2 s + 9
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,
s4 + 1
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
s 4 + 3s 3 − 15s 2 − 2 s + 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. Matlab's function
conv that will do this for you.
x = [1 2];
y = [1 4 8];
z = conv(x,y)
7
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 2
R =
0 0 0 0
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
z=x+y will work (the vectors x and y must have the same length). In the general case,
the user-defined function, polyadd 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 = polyadd(x,y)
x=
1 2
y=
1 4 8
z=
1 5 10
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
9 10 11 12
B = [ 1 2 3 4
5 6 7 8
8
9 10 11 12]
B =
1 2 3 4
5 6 7 8
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 5 9
2 6 10
3 7 11
4 8 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.
D = B * C
D =
30 70 110
70 174 278
110 278 446
D = C * B
D =
107 122 137 152
122 140 158 176
137 158 179 200
152 176 200 224
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 2
3 4
F =
9
2 3
4 5
G =
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.
E^3
ans =
37 54
81 118
If wanted to cube each element in the matrix, just use the element-by-element cubing.
E.^3
ans =
1 8
27 64
X = inv(E)
X =
-2.0000 1.0000
1.5000 -0.5000
or its eigenvalues:
eig(E)
ans =
-0.3723
5.3723
p = poly(E)
p =
10
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:
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.
B =
1 2 3
4 5 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".
MATLAB Tutorial
11
This is an interactive introduction to MATLAB. A sequence of commands, in BOLD
TEXT is provided for you to type in. The designation RET means that you should
type the "return" key; this is implicit after a command.
>>
In the course of the tutorial if you get stuck on what a command means type
and then try the command again. You should record the outcome of the commands
and experiments in a your notebook.
12
Building Matrices
A 7 by 7 matrix with random entries is produced by typing
rand(7)
You can generate random matrices of other sizes and get help on the rand command
within matlab:
rand(2,5)
help rand
hilb(5)
help hilb
magic(5)
help magic
A magic square is a square matrix which has equal sums along all its rows and
columns. We'll use matrix multiplication to check this property a bit later.
Variables
Matlab has built-in variables like pi, eps, and ans. You can learn their values from the
Matlab interpreter.
pi
eps
help eps
At any time you want to know the active variables you can use who:
who
help who
The variable ans will keep track of the last output which was not assigned to another
variable.
13
magic(6)
ans
x = ans
x = [x, eye(6)]
Since you have created a new variable, x, it should appear as an active variable.
who
clear x
who
Functions
a = magic(4)
a'
Note that if the matrix A has complex numbers as entries then the Matlab function
taking A to A' will compute the transpose of the conjugate of A rather than the
transpose of A.
3*a
-a
a+(-a)
b = max(a)
max(b)
Some Matlab functions can return more than one value. In the case of max the
interpreter returns the maximum value and also the column index where the maximum
value occurs.
[m, i] = max(b)
min(a)
14
b = 2*ones(a)
a*b
We can use matrix multiplication to check the "magic" property of magic squares.
A = magic(5)
b = ones(5,1)
A*b
v = ones(1,5)
v*A
Matlab has a convention in which a dot in front of an operation usually changes the
operation. In the case of multiplication, a.*b will perform entry-by-entry
multiplication instead of the usual matrix multiplication.
x = 5
x^2
a*a
a^2
triu(a)
tril(a)
diag(a)
diag(diag(a))
c=rand(4,5)
size(c)
[m,n] = size(c)
d=.5-c
15
There are many functions we apply to scalars, which Matlab can apply to both scalars
and matrices.
sin(d)
exp(d)
log(d)
abs(d)
Matlab has functions to round floating point numbers to integers. These are round, fix,
ceil, and floor.
The next few examples work through this set of commands and a couple more
arithmetic operations.
f=[-.5 .1 .5]
round(f)
fix(f)
ceil(f)
floor(f)
sum(f)
prod(f)
a=[1 0 1 0]
b=[1 1 0 0]
a==b
a<=b
~a
a&b
a & ~a
a | b
a | ~a
16
There is a function to determine if a matrix has at least one nonzero entry, any, as well
as a function to determine if all the entries are nonzero, all.
any(a)
c=zeros(1,4)
d=ones(1,4)
any(c)
all(a)
all(d)
e=[a',b',c',d']
any(e)
all(e)
any(all(e))
Colon Notation
Matlab offers some powerful methods for creating arrays and for taking them apart.
x=-2:1
length(x)
-2:.5:1
-2:.2:1
a=magic(5)
a(2,3)
a(2,:)
a(:,3)
a(2:4,:)
a(:,3:5)
a(2:4,3:5)
17
a(1:2:5,:)
a(:,[1 2 5])
b=rand(5)
a=a(:,5:-1:1)
When you a insert a 0-1 vector into the column position then the columns which
correspond to 1's are displayed.
v=[0 1 0 1 1]
a(:,v)
a(v,:)
This has been a sample of the basic MATLAB functions and the matrix manipulation
techniques. The functions that you have available will vary slightly from version to
version of MATLAB. By typing
help
Miscellaneous Features
You may have discovered by now that MATLAB is case sensitive, that is
casesen
18
Sometimes you will have spent much time creating matrices in the course of your
MATLAB session and you would like to use these same matrices in your next
session. You can save these values in a file by typing
save filename
This creates a file [Link] which contains the values of the variables from your
session. If you do not want to save all variables there are two options. One is to clear
the variables off with the command
clear a b c
which will remove the variables a,b,c. The other option is to use the command
save x y z
which will save the variables x,y,z in the file [Link]. The variables can be
reloaded in a future session by typing
load filename
Scripts
A script is an m-file without the function declaration at the top. A script behaves
differently. When you type who you are given a list of the variables which are in force
during the current session. Suppose that x is one of those variables. When you write a
program using a function file and you use the variable x inside the program, the
program will not use the value of x from your session (unless x was one of the input
values in the function), rather x will have the value appropriate to the program.
Furthermore, unless you declare a new value for x, the program will not change the
value of x from the session. This is very convenient since it means that you do not
have to worry too much about the session variables while your program is running.
All this has happened because of the function declaration. If you do not make that
function declaration, then the variables in your session can be altered.
19
function [output1,output2] = filename(input1,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 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.
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 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 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,
20
300
250
200
150
100
50
0
0 20 40 60 80 100
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 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 colour 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:')
21
300
250
200
150
100
50
0
0 20 40 60 80 100
The third input consists of one to three characters which specify a colour and/or a
point marker type. The list of colours and point markers is as follows:
y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green - solid
b blue * star
w white : dotted
k black -. dashdot
-- 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 colour 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:
22
1
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
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 colour 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) * don't enter this yet
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
23
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);
z = cos(x);
w = tan(x);
subplot(2,2,1)
plot(x,y)
subplot(2,2,2)
plot(x,z)
subplot(2,2,3)
plot(x,w)
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
0 2 4 6 8 0 2 4 6 8
40
20
-20
-40
0 2 4 6 8
As you can see, there are only three plots, even though a 2 x 2 matrix of 4 subplots
were created. This was done 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 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 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).
24
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 y=exp(5t)-1. If you enter
the following into Matlab
t=0:0.01:5;
y=exp(5*t)-1;
plot(t,y)
0
0 1 2 3 4 5
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:
25
50
45
40
35
30
25
20
15
10
0
0 0.2 0.4 0.6 0.8 1
Now this plot is much more useful. You can see more clearly what is going on as the
function moves toward infinity. You can customise 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 labelling, 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')
26
xlabel('time (sec)')
ylabel('position, velocity, or something like
that')
gtext('unnecessary labelling')
The text "unnecessary labelling" was placed right above the position clicked on. The
plot should look like the following:
step response of something
50
45
position, velocity, or something like that
40
35
30
unnecessary labeling
25
20
15
10
0
0 0.2 0.4 0.6 0.8 1
time (sec)
Other commands that can be used with the plot command are:
27
Polyadd Function
function[poly]=polyadd(poly1,poly2)
%polyadd(poly1,poly2) adds two polynominals possibly of uneven length
if length(poly1)<length(poly2)
short=poly1;
long=poly2;
else
short=poly2;
long=poly1;
end
mz=length(long)-length(short);
if mz>0
poly=[zeros(1,mz),short]+long;
else
poly=long+short;
end
28