You are on page 1of 18

ENGG3410 Matlab Tutorial

By: Mike Stachowsky For: Julie Vale

1 Basics
In this tutorial we’ll go over some of the most useful Matlab commands for ENGG3410. Try to
follow along and enter the commands as you see them below. In this document I’ll be showing
you how to enter commands and sometimes will show you what the output from Matlab looks
like. If you want to really understand the commands, though, it’s a good idea to play around
with them on your own beyond what’s in this tutorial. We’ll begin working with Matlab by
introducing some basic ideas. Open Matlab. You should see something like Figure 1 (note: your
screen might be different depending on how the window is set up. For now, we don’t care as
long as you can see the WORKSPACE1 ).

Figure 1: Matlab’s Window

The workspace is where we enter commands. Eventually we’ll see that we can write code in
separate files, but for now we’ll stick to the workspace.
The first thing we usually do is clear all of the variables in the workspace. This is useful if
you accidentally make a mistake, and should always be done before you want to start on another
project. To clear the workspace, type

>> clear all

Be careful! This will delete all of your variables, so make sure you want to do this before going
ahead and doing it!
1
And, to be honest, most of the time as long as we can see the workspace we don’t care about the rest of it...

1
2 Basic variables
Although Matlab can be used like a calculator, it’s more useful to store data in variables for
further processing. In Matlab, it’s easy to declare a variable. You just type a variable name and
then set it equal to something, like this:

>> x = 5;

You should see a variable called “x” showing up in the section labelled Variables in your
Matlab window. Notice how I put a semicolon at the end of the statement. In Matlab, doing
this is not necessary: the command would still work. The semicolon just suppresses the output
to the screen. Below is what happens when you keep the semicolon there and when you remove
it.

>> x = 5;
>> x = 5

x =

If you’re doing something with very large arrays of numbers and you forget a semicolon it might
take longer to print your output than it takes to actually run your code! For this reason, I
suggest that you always use a semicolon unless you know you want to see the output.
If you want to see what the value of the variable is, just type its name into the workspace.

>> x

x =

Variable names work the same as they do in most programming languages: you can name your
variables anything as long as they start with a letter. Numbers can be included in variable
names as long as they aren’t the first thing. For example,

>> 1x = 5;

will produce an error, while

>> x1 = 5;

will produce a variable in your workspace called x1, which will show up in the “Variables” section
of Figure 1.
Basic math operations work just like you’d expect them to:

>>x + x1

2
will output the number 10 but will not store the result in a permanent variable2 . If you want
to store the result to a variable, you can do that too:

>> y = x + x1;

will create a new variable, y, whose value is 10. On the other hand,

>> x1 = x + x1;

will reset the value of x1 to 10. Other basic operations include multiplication, division, and
raising to a power. To multiply two variables, use the * symbol:

>> x2 = x*x1;

which will result in a variable, x2, being set to a value of 50 (remember, we’ve already set x1 to
10 above!). To divide, we use the / symbol

>> x3 = x/x1

which will result in a variable, x3, whose value is 0.5. Mathematically you can’t divide by 0 but
Matlab lets you do it without producing an error:

>> 5/0

ans =

Inf

will produce a special Matlab constant called “Inf”, for “infinity”. We will be avoiding Inf as
much as possible, since it causes some surprising problems that we’d rather not deal with3 .
Finally, to raise a variable to a power, we use the ^ symbol:

>> x4 = x^5;

which will raise x to the power of 5 (so x4 = 55 ).


2.1 Matrices and Vectors
Matlab excels at far more than just basic math. It’s true power lies in its ability to work with
matrices and vectors. Vectors and matrices can be declared like variables. To do so, you use
square brackets like this:

>> v = [1,3,4];

this creates a 1x3 vector whose entries are 1, 3, and 4.


2
Strictly speaking this isn’t true. Matlab stores results of expressions like this in a variable called “ans”, which
is just another variable in your workspace. However, every time you make an expression like this it will overwrite
“ans”, so try not to rely on this too much.
3
Inf + anything = Inf and Inf*anything = Inf, but anything/Inf = 0. Inf is Matlab’s way of saying “This
number is too large for me to handle. Something went wrong in your code”

3
>> v1 = [1 3 4];

does the same thing, with the spaces acting just like the commas, but

>> v2 = [1;3;4];

creates a 3x1 vector whose entries are 1, 3, and 4 . If you want to make a matrix, you use a
combination of commas (or spaces) and semicolons. For example, a 2x2 matrix is created like
this:

>> mtx = [1,2;3,4];

so, the elements of each row are separated by commas (or spaces), and the rows themselves are
separated by semicolons. To test this out, create a 2x3 matrix with any numbers you want. Call
it mtx1 and output it to the screen. Make sure you got the dimensions right. We will be using
mtx1 in some examples below.
Matrix multiplication works in two ways. If we want to multiply mtx*mtx1, and store it in
a variable called mtx2, we can do that by entering this command:

>> mtx2 = mtx * mtx1

remember from linear algebra that the order in which we multiply matrices is important. In
general, it is not true that A*B = B*A. In fact, the following command will result in an error.

>> mtx3 = mtx1 * mtx

It’s an error because we can’t multiply a 2x3 matrix with a 2x2 matrix. The dimensions don’t
work! However, the dimensions will work if we transpose the matrix mtx14 . In Matlab, trans-
posing a matrix, or a vector, is achieved by adding an apostrophe at the end of the variable
name. The following command will not result in an error:

>> mtx4 = mtx1’ * mtx

Here is a brief excersize that will help you understand this a little better. Create a 1x2
vector, called v3, whose first entry is 5 and second entry is 4. The following command will result
in an error. Add a transpose operation in the appropriate spot to fix it.

>> mtx5 = mtx * v3;

Now verify that the following command is equivalent to the dot product between v and itself:

>> vDot = v*v’;

Sometimes we don’t want to work with matrix multiplication. For example, we want to
raise every element in a vector to a power. The following command will cause an error, because
mathematically it doesn’t make sense.

>> vp = v^2;
4
although, of course the result still won’t be the same as mtx * mtx1!

4
We cannot raise a vector to a power. But we didn’t want to do that in the first place; we wanted
a vector whose elements are the squares of the elements in v. To do this Matlab has a built
in operator that we can put in front of any other math operation and turn it from “matrix
operation” to “element-wise operation”. This is the period, or dot, and it’s used like this:

>> vp = v.^2

usually we say “vp equals v dot-squared” or something like that. Mathematically, vp will be a
vector that looks like this:

vp = (1 32 42 ) = (1 9 16) (1)
We can use the dot operation for multiplication and division as well, as follows:

>> vp1 = v.*v

This is a vector with the same elements as in vp, since it is the same thing as squaring the vector
element-wise. To divide, we do the following:

>> vp2 = v./vp1

This is a vector whose elements are equal to the elements of v divided by the respective elements
of vp1. Warning! The following code may not throw an error (whether it does or not depends
on the version of Matlab you’re using):

>> vp3 = v/vp1

In newer versions of Matlab, this takes the pseudo-inverse, which is a creature from the depths
of linear algebra that is often useful for solving systems of linear equations. Be very careful with
division: if you mean to divide element-wise, use the dot. If you really wanted the pseudo-inverse,
then don’t add the dot.
Dot-operations work for matrices as well; for example,

>> mtx5 = mtx.^2

produces a matrix whose elements are the squares of the elements in mtx.
I should mention one key point about dot operations: the two variables you are dot operating
on must have the same size. The following code will cause an error:

>> g = mtx.*v

because mtx is 2x2 and v is 1x3: there are simply not enough elements in v, and they are
not arranged properly, to perform this operation. However, recall from linear algebra that it is
possible to raise a square matrix to a power. The following code is valid without the dot:

>> mtx6 = mtx^2

5
show that mtx6 does not equal mtx5, then be very careful in the future about using the dot
operations. This is a common sticking point with Matlab, so be sure that you know which one
you meant.
To wrap up our discussion on basic matrix operations, we will introduce two familiar matrix
operations that used to be extremely irritating to do by hand: inversion and determinant.
Luckily, Matlab has built in functions for these as well.

>> g1 = inv(mtx)

produces the inverse of the matrix mtx. If the matrix is not invertible, Matlab will give you a
warning, and that infamous Inf will pop up again. For example, the following set of commands
and Matlab output are what you get when you try to invert a matrix that cannot be inverted:

>> mtxN = [0,0;0,0]

mtxN =

0 0
0 0

>> inv(mtxN)
Warning: Matrix is singular to working precision.

ans =

Inf Inf
Inf Inf

Recall from linear algebra that a matrix is not invertible if its determinant is zero. Matlab
lets you check the determinant of a matrix with the “det” command. It is used as follows:

>> d = det(mtx)

what is the determinant of mtxN?5


You may have realized by now that, if we had to construct vectors and matrices by hand
every time, it would quickly become annoying. Luckily, Matlab allows you to specify matrices
based on a number of rules.
Let’s do this via an example. When working with dynamical systems in Matlab, it’s often
very useful to have a vector filled with times at which the simulation will take place. For instance,
we want to simulate the output of a second order system from 0 seconds to 100 seconds, and we
want to observe the output five times per second, or every 1/5 of a second. To accomplish this,
we should make a vector of times. This is achieved by using the colon operation as follows:

t = 0:1/5:100;
5
I’ll give you a hint: it’s 0. But you should show that using Matlab.

6
this will create our vector of times. Notice that I put a semicolon at the end. If I hadn’t, then
Matlab would dutifully print out all 501 elements of t. It’s worth repeating that if you are
working with very large vectors, this can often take far longer to print than the code takes to
run, so be careful with your semicolons6 .
Another useful operation is to make a vector of numbers that increment by 1. This is
particularly useful to count things. You can do this in one of two ways.

>> t1 = 0:1:100;

or

>> t2 = 0:100;

both are equivalent. In general, Matlab will default to a spacing of 1 between elements if you
don’t specify, which is why the command that generates t2 does not throw an error.
What happens if we know we want 543 equally spaced points, but those points are between
weird numbers, like 3.423 and 5.667?7 We could, if we were very bored, figure out the spacing
ourselves, or we could just use the “linspace” command like this:

>> t3 = linspace(3.423,5.667,543);

This produces a vector of 543 equally spaced points between the numbers 3.423 and 5.667.
Equal spacing is important when you’re simulating the output of a dynamical system, since
most numerical solvers require that the time vector be equally spaced8 .
Now that we’ve made a few vectors, you might be thinking that if we can’t access the
elements of a vector, this is all pretty useless. So, we need to look at how we access elements of
a vector. Let’s say that we wanted to know what the 300th element of t3 is. Matlab, unlike other
programming languages you might be familiar with, starts indexing the elements of a vector at
1, not 0. So,

>> t3(1)

is the first element of t3, while t3(300) is the 300th. Often, we want to get a whole range of
elements from a vector. Matlab lets us do this by using...another vector! Let’s say we want all
the elements in t3 from index 300 to index 400. We can do this in two ways. The first is to do
this:

>> indx = 300:400;


>> t4 = t3(indx);

Here we’ve treated the vector “indx” as though it were just a set of element numbers9 . The
second way is to just do this implicitly, like this:
6
It’s also worth mentioning that if your code is ever doing something strange like trying to print out a billion
elements of a vector, type CTRL+C at any time to stop the code. You might lose work, but if it’s a small bug to
fix it could mean the difference between running the code for a day and running it for a few seconds!
7
This happens a lot when we are dealing with data taken from the real world, since you aren’t ensured you’ll
get a nice round number of samples, for example.
8
I should mention that there are a lot of “variable step” solvers, but we won’t be worrying about those, since
Matlab is generally smart enough to figure things out on its own. If you’re really interested, find a book on
numerical methods and get cracking.
9
This is why a vector with spacing of 1 between elements is useful!

7
>> t5 = t3(300:400);

both work perfectly fine, but the first option lets us be very clear in what we mean, and we can
re-use the vector indx in other data if we wanted to get the same information from a number of
vectors. If we want to get part of a matrix, we use the same idea, but we separate the rows and
the columns with a comma. So,

>> mtxSmall = mtx(1,2)

returns the element in row 1, column 2, of the matrix mtx that we created earlier.
There are some interesting special ways to make common matrices or vectors. Matlab lets
us make a matrix consisting of all zeros, all ones, a diagonal matrix, or the identity matrix, with
these four built in commands:
To produce a matrix of all ones, you use the “ones” command:

>> mtxOnes = ones(4,4)

will produce a 4x4 matrix of all ones. To produce a matrix of all zeros, you use the “zeros”
command:

>> mtxZeros = zeros(3,5)

produces a 3x5 matrix of all zeros. To produce a diagonal matrix from a vector, you use the
“diag” command:

>> mtxDiag = diag(v)

produces a 3x3 diagonal matrix whose diagonal entries are the same as the entries of the vector
v. Finally, to create the identity matrix, you use the “eye” command:

>> mtxI = eye(5);

produces the 5x5 identity matrix. It might seem strange to make a matrix of all zeros or all ones,
but we’ll be using both of these commands below to create inputs for our transfer functions. A
quick example will show you how we might accomplish this.
As we saw above, when we are simulating dynamical systems we often start with a vector
of times. The inputs to the system are supposed to come one after the other, one for each time
step. So if we did this:

>> ti = 0:0.01:100;

to make a vector of times, we will want to make a vector of inputs that is the same size. Matlab
lets us do this using commands like ones or zeros, along with a special command called “size”,
that works like this:

>> u = zeros(size(ti));

This produces a vector of zeroes that has the same size as the vector ti.

8
2.2 Putting this all together
In this example, we are going to make a time-vector that starts at 1, increments in steps of one
second, and stops at 100. We are then going to make a step input that is the same size as this
time vector. It will have the step occur at 50 seconds, and have an amplitude of 4.
The first step is to make the time vector:

>> tt = 1:100;

Now we want to make an input vector, call it u1, that is the same size as tt but is made of all
zeros. We want it to be all zeros because we need it to exist in memory before we can use it,
and as we stated the problem, the input is zero until 50 seconds. Therefore it makes sense to
start with a vector of zeros and then modify that.

>> u1 = zeros(size(tt));

Finally, we want u1 to be equal to 4 for after 50 seconds. We do this as follows:

>> u1(50:100) = 4;

And that’s that! Let’s move on to a few useful commands that will help you with your labs.

3 Useful Commands for your Labs


3.1 Plot
Probably the most important aspect of analyzing data is being able to see what it looks like.
Matlab’s “plot” command lets you plot 2D data10 . To use plot, you have to supply an indepen-
dent and a dependent variable; for example:

>> u2 = ones(size(tt));
>> u2(50:100) = 4;
>> plot(tt,u2);

This should pop up a figure that shows you a plot of u2 vs. tt, with tt on the x axis and u2 on
the y axis (see Figure 2).
Now, you might have noticed that our new plot looks weird: it’s hard to see the step. In
general, Matlab will set the axes of the figure to be as small as they need to be to contain all
of the data. For our purposes, this is not very good, since most of the data occurs right at the
limits. So we’re going to use the “axis” command to fix that. Keep the plot open, then type in
the workspace:

>> axis([0,100,0,5]);

Now look at your plot (or just take a look at Figure 3). Notice how the axes have changed?
Axis’ arguments are: axis([xMin, xMax, yMin, yMax]); So, whenever you see a plot that doesn’t
look right, try changing the axes. Remember, the command “axis” will change the axes. The
command “axes” (notice the plural) is different and rarely used.
Plot has some other useful options. For example, if you tried to plot another data set,
Matlab will over-write what’s on the existing figure. So if you want to make two figures, you
use, conveniently enough, the “figure” command:
10
although there are many other commands that let you do things like 3D visualizing or movies, we’re not going
to go into them here

9
Figure 2: Our first plot

Figure 3: Our first plot, made better

10
>> plot(tt,u2);
>> figure(6)
>> plot(tt,zeros(size(tt)));

Notice how this plots a second figure, and its figure number is 6. The figure numbers are
arbitrary, and as long as they are unique you won’t overwrite your existing figures.
The above command made us two figures with different data. If, instead, you wanted to have
the second plot on the same figure, but without erasing the first data set, you use the “hold on”
or “hold off” commands. “hold on” lets you plot on the same figure. But be careful. If the two
datasets aren’t close to the same size, you might get some strange looking plots.
Close any figures that are now open11 , and try this:

>> u3 = zeros(size(tt));
>> u3(25:50) = 2;
>> plot(tt,u2);
>> hold on
>> plot(tt, u3);
>> axis([0,100,-1,5])

Figure 4: Two plots in one

You should see the two plots showing up on one figure, like in Figure 4. Notice how this figure
looks a bit messy. Both plots are the same color, and they seem to blend together. To change
the color of a plot, we can add a few arguments to the plot command. Close all the figures you
now have open. If we want to plot the second plot in red, we do this (see Figure 5):

>> plot(tt,u2);
>> hold on
>> plot(tt,u3,’r’);
>> axis([0,100,-1,5])

Notice that the letter r, for red, is in single quotes. Some other colors to use are ‘k’, for black,
‘b’, for blue, ‘g’ for green, ‘c’ for cyan. It’s best to avoid light colors, like ‘y’ (yellow), since they
don’t often show up very well when printed.
11
Or use the “close all” command, which will close every figure that’s open.

11
Figure 5: A bit easier to see

Before we move on from plot, there are a few more useful commands to know. Keep the
previous figure open. If you want to make it easier to find a data point, you can turn on a grid
using the “grid” command.

>> grid on

This turns the grid on. (“ grid off” turns it off)

>> grid minor

This makes the grid smaller (type it again to turn off the smaller grid).
Finally, plots are confusing unless we can label them. We do this with “xlabel”, “ylabel”,
and “title”, for the x axis label, y axis label, and title, respectively. Keep your plot open. Use
these commands like this:

>> xlabel(‘time’);
>> ylabel(‘Input’);
>> title(‘Two inputs against time’);

Notice that the strings are in single quotes! Double quotes won’t work in Matlab for this
purpose12 .
Finally, if you want to actually see what the data is, use the datatip tool (circled in Figure 7).
Click the tool, then click on your plot, and it will tell you the coordinates of the data.
3.2 TF
Finally! Something to do with control theory. As long as you have the “Control System” toolbox
(all school computers should have this) you can make transfer functions and play around with
them to your heart’s content. To do that, we use the “tf” command, which makes a transfer
function in the s-domain. You supply it two vectors: the coefficients of the numerator and of
the denominator; for example, to make a first order system without any zeros and a gain of 1,
we do this:
12
I actually have no idea what double quotes do in Matlab. I imagine they must do something, but they are so
rarely used that I don’t know what it is...

12
Figure 6: Everything at once

Figure 7: Datatip

13
>> num =1

num =

>> den = [5,1]

den =

5 1

>> s1 = tf(num,den)

Transfer function:
1
-------
5 s + 1

If we wanted to add zeros, or increase the order, we just play with the numerator and denom-
inators. Warning: Matlab will happily make whatever transfer function you give it. So, for
example,

>> num = [5,4,3];


>> den = [1,2];
>> s2 = tf(num,den);

does give you a system. It is, however, not a proper transfer function, so Matlab is going to
have trouble working with it in the future. Although Matlab can construct non-proper transfer
functions, it is not capable of doing any simulation of their responses.
A final command that’s useful for transfer functions is “minreal”. It handles any pole/zero
cancellations that might be present in a transfer function, and produces a minimal order transfer
function; for example, if I make a transfer function with one pole at s = 1, one pole at s = 2,
and two zeros at s = 1, minreal will handle the cancellation of the pole and one of the zeros.

>> num = [1 -2 1];


>> den = [1 -3 2];
>> tfMax = tf(num,den)

Transfer function:
s^2 - 2 s + 1
-------------
s^2 - 3 s + 2

>> minreal(tfMax)

Transfer function:
s - 1

14
-----
s - 2

minreal is extremely important in this course. All of your transfer functions should be minimal
before you work with them!
3.3 Working with Transfer Functions
Since it would be tedious to create input vectors every time we wanted to see a step response,
we’ll now go through a number of common simulation commands that you’ll find useful for
working with transfer functions. The first is “step”, which simulates the step response of the
system and plots it.

>> step(s1)

The next is “impulse”, which simulates the impulse response and plots it.

>> figure(8)
>> impulse(s1)

Figure 8 and 9 show the step and impulse response of the system s1. Notice that neither
command will work on the system s2, since it is non proper, so

>> step(s2)

will throw an error.

Figure 8: Step

step and impulse can be limiting, though. If you want to simulate the output of the system to
an arbitrary input, you use the “lsim” command13 . lsim takes a system, an input vector, and a
time vector, and plots the output of the system to those inputs. Use it like this:

>> lsim(s1,u1,tt);

15
Figure 9: Impulse

Figure 10: lsim

16
Notice that lsim also plots for you (see Figure 10). So now you can plot the response of your
system to any input, as long as you can describe it in vector form. Notice also that the order is
important here: first you tell lsim which system it’s working with, then you give it the inputs,
then the time vector. Don’t switch these around unless you want to see some very odd behaviour
indeed.
Finally, lsim won’t work on a non proper transfer function, just like step and impulse.
You may have learned that Bode diagrams let you analyze a transfer function’s frequency
and phase response. Naturally, the good folks at the Mathworks learned this a while back, too,
and they implemented the “bode” function that does just that.

>> bode(s1);

will plot s1’s bode diagram (see Figure 11). What happens if you try to plot the bode diagram
of s2? You might be surprised...it actually works! Although Matlab can’t simulate non proper
transfer functions, it can still use tools like bode to analyze them.

Figure 11: Bode plot of s1

4 Storing your work: M-Files


The final thing we’ll go through is creating m-files. So far we’ve been typing into the terminal,
which is great, but if we want to make a bigger project (or, in the future, take advantage of
things like for loops or if statements), we need to be able to write all of our code in one place,
then execute it all at once. This is what m-files do. m-files are also very useful to repeat tedious
calculations where you need to change the values of only a few variables. In the Matlab window,
go to file →new→script. You’ll see a text editor open up.
Creating an m-file works exactly like writing in the terminal, except the code only gets
executed once you tell Matlab to run it. Commands must go on a separate line, but other than
that everything you can do in a terminal can be done in an m-file. Here is a sample that you
can copy and paste into your editor:

x = 1:10;
%this is a comment. Comments don’t get executed. You start them with the ‘‘%" sign
13
And...a lot of tedious generation of vectors, but it’s not that bad...

17
%and they last for one line (which is why this line needed a new % sign)
y = x.^2;
plot(x,y)
To run this file, save it as test1.m, then go to the Matlab workspace and type
>> test1
You should see the plot pop up. Notice that the command to run the m-file is the same as the
m-file’s filename. If we had called it “donkey4.m”, then running it would mean you type the
command “donkey4” into the workspace. You could also have hit the F5 key to run it when you
were still in m-file’s window, or clicked the green “Play” icon in the m-file’s window.
You can name m-files in exactly the same way as you name variables. Just be careful not
to name an m-file the same thing as a variable, or else you’ll confuse Matlab. Also be careful
that you aren’t naming your m-files something that Matlab already uses. For example, you are
allowed to name an m-file “bode.m”, but then the behaviour might be strange. Which version
of bode Matlab uses will depend on which folder you’re in. To make sure you aren’t doing this
accidentally, whenever you come up with a new name for something that sounds like it might
already be used, try typing it into the workspace. If Matlab tells you that no variable or function
with that name exists, you’re fine. Otherwise it might throw an error, assuming you meant to
actually run the function. If Matlab isn’t already using the name, it looks like this:
>> vale
??? Undefined function or variable ’vale’.
This indicates that the name “vale” is safe to use.

5 Help, Doc, and Google: Matlab’s hidden treasures


Oh no! You’ve forgotten how to plot! Or make a bode diagram...or anything. There is a lot to
learn about Matlab, and it’s not realistic to have to remember everything all at once. Luckily,
Matlab comes with three incredible features that help you along the way.
HELP: if you don’t know how to use something, but have a pretty good idea what it does,
use the help command. This brings up information about how to use any command that Matlab
has to offer; for example:
>> help bode
tells you more than you ever wanted to know about how to use bode. Did you notice that it has
more features than I showed you?
If you want something prettier, with links to other help files and maybe even some pictures,
then use the “doc” command. This pops up Matlab’s built-in documentation.
>> doc step
Opens up a nice little web-page style information box that can really come in handy.
Finally, what happens if you’re completely stuck, totally forgot what the command was even
called, and have no idea if Matlab can even DO what you’re asking? Matlab comes with another
great feature called Google (haha). If you forgot that the “tf” command exists, googling “Matlab
transfer function” will probably set you right. Often, but not always, the first link to pop up is
from the mathworks anyway, with the exact command you need.
Of course, if you’re really stuck, you have dedicated TAs and professor who can help out as
well.

18

You might also like