You are on page 1of 14

MM114 Engineering Mathematics (Applications)

Introduction to Matlab: Matlab Reference Notes

The pictures in these notes show Matlab 2014a. All recent versions of Matlab
look very similar, and all of the commands work in the same way.

The Matlab Window


When Matlab starts, you should see something like the picture below:

Files in
Current
Directory Workspace
Command
Window

Current Directory

As well as the usual toolbars and menus, there are three important areas in the
Matlab window:

 The Command Window where we type commands, and Matlab displays


information and results.
 The Workspace which shows variables, matrices, etc which we have
defined. The workspace also has a tab which acts as a file manager,
although we will not use that in this tutorial.
 The Current Directory and its list of files show files which Matlab can
open, either by typing commands in the command window, or by double-
clicking them.

1
Extra Windows

The Layout button on the Home tab allows us to pick extra windows which might
contain useful information or allow us to do useful things:

“Docked” windows are fitted into the arrangement in the main Matlab window,
while “Popup” windows have their own, separate window. The Command
History window shows a list of commands which have been previously issued in
the Command Window: double-click on one to repeat it without retyping it.

The Command Window can also share its space with the Variable Editor – a
spreadsheet-like window which lets us inspect and change the contents of
variables. You can open the Variable Editor by double-clicking on a variable in the
Workspace:

Variable Workspace:
editor Variable a
selected

Command
Window

The Command Window


Generally, we get Matlab to do things by typing commands in the Command
Window. Remember to press the ENTER key after each command. The Command

2
Windows shows the >> symbol when it’s ready to receive a command. This is
shown in the examples below.
You can repeat a previous command by using the up and down arrows to look
through previous commands and pressing the ENTER key when you see the one
you want. Alternatively, you can use the mouse to look through the commands
shown in the Command History window, and double-click on the one you want.
You can cut-and-paste from the Command History to the Command Window.
Often, when you issue a command, Matlab will display the result in the Command
Window. This is shown in the examples below.

Variables and Workspaces


We can store values in Matlab variables. The set of variables which are in use at
any time is called the Workspace, and is shown in the Workspace window.
To define a variable, or to change the value of an existing variable, type an
assignment command in the Command Window. Remember to press the ENTER
key afterwards. For example, to assign the value 12 to a variable called x, type:

>> x=12

Notice that Matlab displays the name and value of the variable as confirmation. Or,
to assign the value 1375.1 to a variable called y:
>> y=1375.1
y =
1.3751e+003

Notice that Matlab is displaying the value of y in scientific notation. 1.3751e+003


means 1.3751103 .
You can also change the value of a variable in the Variable Editor.
To check the value of a variable you can:
 Look in the Workspace window. For complicated variables (like matrices
and vectors), the actual value of the variable is not shown here, but only a
description of the type of value.
 Double-click on the variable in the Workspace window to see it in the
Variable Editor. You can scroll through large vectors here.
 Type the name of the variable in the Command Window and press ENTER.
Matlab will display the value of the variable. For example:
>> x
x =
12

Loading and Saving Workspaces


Matlab workspaces can be saved and loaded to and from files. This is useful in
working with data provided by someone else, submitting Matlab-based
assignments for this class, and (in projects later in your degree) keeping your
work safe from week to week.

3
Saving the current MATLAB workspace
Matlab’s workspace can be saved using the Save Workspace button on the
Home tab, or by using the save command at the command line:
>> save('filename')

File names are automatically given a ‘.mat’ extension. If you use the save
command, saved workspace files are put in the Current Directory shown at the top
of the Matlab window, which can be changed by selecting from the drop-down list,
or selecting from the Current Directory window.

Loading a saved workspace


A previously saved workspace can be reloaded by double-clicking it in the Current
Directory window, or by clicking the Open button on the Home tab – unless you
tell it otherwise, this will show you all files that Matlab can open, not just
workspaces. From the command line, you can use the load command:
>> load('filename')

As before, filenames are automatically assumed to have a ‘.mat’ extension, and are
taken from the Current Directory. If the specified saved workspace file doesn’t
exist, you’ll see an error message
??? Error using ==> load
Unable to read file x: No such file or directory.

Loaded workspaces are added to the current workspace (so you get extra
variables, but may not lose all the existing ones), so it is advisable to clear the
current workspace before loading a saved workspace.

Clearing the workspace


Matlab’s workspace is cleared using the clear command:
>> clear

This removes all variables from the workspace

Example
1. Create a variable A with value 4.
>> A=4
A =
4
2. Save the workspace to the Desktop with name ‘example’.
>> save('example')
3. Check the value of A by typing ‘A’ and pressing Enter
>> A
A =
4
4. Clear the workspace
>> clear
5. Notice that A has vanished from the workspace. Check by typing ‘A’ again.
>> A
??? Undefined function or variable 'A'.

4
6. Load the ‘example’ workspace. Check that A has now reappeared with its
old value
>> load('example')
>> A
A =
4
7. Change the value of A to 5, and create a new variable B with value 3
>> A=5
A =
5
>> B=3
B =
3
8. Load the ‘example’ workspace
>> load('example')
9. Check the values of A and B
>> A
A =
4
>> B
B =
3
10. A has retaken its saved value, but B is still present

Functions and Equations


You can use Matlab as a calculator by typing a calculation in the Command
Window using the usual symbols:

+ add (e.g. 2+4) * multiply (e.g. 4*2  4 2 )


- subtract (e.g. 4-2) / divide (e.g. 4/2  4  2 )
() brackets control the order of ^ power (e.g. 4^2  4 2 )
operations

The order in which the calculation is done is:

1. Brackets, working from the inside outwards


2. Powers
3. Multiplication and division
4. Addition and subtraction

For example:
>> 3*2+7
ans =
13
>> (120+105)/5^2
ans =
9

You can assign the results of these calculations to variables:


>> boxvolume=12.3*11.9*5
boxvolume =
731.8500

5
>> floorarea=98.7^2
floorarea =
9.7417e+003

You can use variables on the right-hand-side of a calculation to make an equation.


However you must always use the operator symbols:

3*y not 3y

For example:
>> freespace=floorarea*3.2-boxvolume
freespace =
3.0442e+004

Notice that Matlab has rounded to 5 significant figures in displaying the result.
However, the variable stores the result more accurately:
>> freespace-3e+4
ans =
441.5580

Sequences of values
As well as variables which store a single value, we can store variables which store
sequences of values. This is useful, for example, if we want to investigate how a
quantity changes over time, or if we want to plot a series of points on a graph.

To put a sequence of values in a variable, we put them in square brackets:


>> x = [1,3,5,7,9]
x =
1 3 5 7 9

Looking at x in the Variable Editor shows that the values are laid out in a row. To
put them in a column, replace the commas with semicolons:
>> y = [2;4;6;8;10]
y =
2
4
6
8
10

Technically, Matlab is putting these values into a matrix. We will look at matrices
in more detail in a future week.

If we have lots of values (e.g. one for every hour of a year – that’s 8760) it would
be very tedious to have to type them all out. If they are regularly spaced, then
Matlab has a handy shortcut:
>> z=[1:2:7]
z =
1 3 5 7

[start:interval:end] tells Matlab to create a variable in which every intervalth


number from start to end inclusive is put into the variable.

6
The numbers are put into a row. If we want a column, we have to use the matrix
transpose operator ' to change the row into a column:
>> w=[3:3:9]'
w =
3
6
9

Equations using Sequences


Most of the time, we can use variables containing a sequence of numbers as if they
were ordinary variables. The result is a sequence of numbers, which you can
assign to a variable:

>> t=w*2
t =
6
12
18

Sometimes, Matlab will try to use special matrix operations on a variable


containing a sequence of numbers, when we actually want it to treat each number
in the sequence individually:

>> r=2^w
??? Error using ==> mpower
Matrix must be square.

When this happens, we have to tell Matlab explicitly to treat the numbers in the
sequence individually by putting a dot in front of the operator:

>> r=2.^w
r =
8
64
512

Similar things can happen when multiplying and dividing. In both cases, add a dot
(.* and ./) to resolve the confusion.

>> s=r*w
??? Error using ==> mtimes
Vectors must be the same lengths.

>> s=r.*w
s =
24
384
4608

7
Plotting Graphs
To plot a graph, use the plot command. Two sequences of numbers are required
(one for the x-axis, and one for the y-axis) which must have the same number of
elements.

Let’s assume we have the following variables:


t = 0 1 2 3 4 5 6 7 8 9
I = 0 1.1 1.5 1.7 1.9 2.3 2.4 2.8 2.7 2.5
V = 0 2.5 2.8 2.9 3.1 3.2 3.0 2.9 2.9 3.0

To plot a graph of I (y-axis) against t (x-axis):


>> plot(t,I)

A new window will open showing the graph:

I
values

t
values

If the sequences were of different lengths we would see this error:


??? Error using ==> plot
Vectors must be the same lengths.

8
To plot two (or more curves) on the same axes, we give the plot command
additional pairs of x- and y-values:
>> plot(t,I,t,V)

Results in:

I and V
values

t
values

Notice that both I and V are plotted on the same scale.

Saving and Loading Graphs


Matlab will save and load graphs to and from files. This is useful for saving rough
results for formatting them (or adding more data) later, or for adding them to
reports or assignments.

To save your graph, click the save button ( ) on the graph window. If you have
previously saved your graph, this will replace the saved copy with an up-to-date
version. Otherwise, a dialog box will open, which will let you specify the name of
the saved file, and the format to use. Click the “Save as type” list box to see all the
file formats that Matlab can produce.

There are two important sets of file formats:

 Matlab’s own “.fig” format: This saves all the information associated with
the file, so you can go back and edit it later – for example changing the
scales or line colours, or even adding extra data.
 Picture formats like GIF, JPEG and PNG: These let you add your graphs
to reports, presentations and web pages. However, your graph is turned
into a picture; you can’t change it later.

If you want to change the format of a graph file (for example, to have a “.fig” file
to work some more on later, and a picture to put in a report), use “Save As” on
the File menu.

9
To load a previously-saved graph, click the load button ( ) and select the file you
want. You can only load graphs in the “.fig” format. Picture formats like JPEG will
not work.

Formatting Graphs
To format the graph, open the Plot Tools using the button ( ) on the graph
window:

Plot
Tools

10
The graph window will expand to show some extra elements:

Plot
Browser

Graph
Figure
Palette

Property
Editor

The Graph appears top-centre, between the Figure Palette, which allows us to
add extra elements to the graph, and the Plot Browser. The Plot Browser lets us
select elements of the graph in order to modify their appearance using the
Property Editor.

The plot browser contains one entry for the graph axes, and one for each line on
the graph. The lines can be made to appear and disappear by checking and
unchecking the boxes in the Plot Browser.

Clicking the entry for the axes makes the Property Editor show formatting
information for the graph as a whole, and for the axes:

Graph Axes

Here, you can give the graph a title, and add titles and units to the axes. Your
changes take effect as you type (or in some cases when you click in a different part

11
of the window). You can change the scales of the axes if the scales Matlab initially
provides aren’t suitable.

Clicking on an entry in the Plot Browser for a line in the graph makes the property
editor show formatting information for that line:

Here, you can give your line a name (important if you have more than one line on
your graph and need to add a legend) and change its colour and style.

You can also format many elements of the graph by right-clicking on them. Right-
clicking on the white background of the graph will let you add a grid or a legend:

You can move the legend by clicking and dragging with the mouse if Matlab puts
it in an inconvenient place.

12
Adding Data to a Graph
To add data to an existing graph (without drawing a new one from scratch), select
the axes in the Plot Browser and click the Add Data… button. A window will appear
for you to choose the values for the x- and y-axes of the new line:

If your x- and y-variables have different lengths, an error message will appear, and
the line will not be added to the graph.

Don’t leave the source for the x-axis data at “auto” – this will make the x-values of
your points 1, 2, 3, etc. This will also happen if you drag the variable onto the graph
from the Figure Palette.

13
Index
Over the next few weeks, you will explore several aspects of Matlab’s capabilities,
which will be described in sets of reference notes like this. The index will help you
to find particular topics among this information.
Topic Term Week Page
Adding Data to a Graph 2 8 13
The Command Window 2 8 2
Equations using Sequences 2 8 7
Formatting Graphs 2 8 10
Functions and Equations 2 8 5
Loading and Saving Workspaces 2 8 3
The Matlab Window 2 8 1
Plotting Graphs 2 8 8
Saving and Loading Graphs 2 8 9
Sequences of values 2 8 6
Variables and Workspaces 2 8 3

Errors
The table below lists the text of some common errors, and will help you to find the
worksheet which mentions them
Error Term Week Page
Matrix must be square. 2 8 7
Unable to read file x: No such file 2 8 4
or directory.
Undefined function or variable 'A'. 2 8 4
Vectors must be the same lengths. 2 8 7
2 8 8

14

You might also like