You are on page 1of 19

An Introduction to MATLAB

Version 1.1
Department of Mathematical Sciences, University of Bath

0 Introduction
0.1 What is MATLAB?
MATLAB is a programming language, just like C, Python, and many others. MATLAB also refers to the
editor you will be using to write scripts and functions in this language. If youve already learnt a
programming language, you might find it easy to transition to MATLAB. However, if you have never
tried programming before, some of the concepts may seem foreign and a little daunting. The
purpose of this guide is to attempt to bridge the gap for those who have no prior knowledge of
coding and allow them to take the first steps towards learning a programming language.
0.2 About this guide
This guide has been written by student volunteers, and is constantly in the process of being edited
and rewritten to improve it and make it more accessible to students. Because of this, there may be
some mistakes and room for improvement. If you would like to help with the writing of this guide or
offer suggestions and corrections, please email a.spence@bath.ac.uk.

1 Getting started with MATLAB


1.1 The Interface
Once you open MATLAB, you will be presented with an interface like the one below.

Command Window: This is the main workspace where you will type your commands. The

prompt symbol (>>) shows that MATLAB is ready for you to type a command.
Current Folder: Once you start writing and saving functions, you will need to be in the correct

folder in order to use a function. Double-click on a folder to open it. If you are in the correct folder,
the file names will be in black; if you are not in that folder, the file names will appear in grey with a
faded icon beside them.
Workspace: Once you begin using variables, MATLAB will show you which variables are stored by

saving their values in this panel. If you want more information about a variable that is stored,
double-click on its name and a new panel will open, showing its details.
Command History: This is a list of the previous commands you have entered into the command

window. If you want to use a command again without typing it all out, you can double-click on a
command in this panel to run it.
Current Location: Here you can check which folder you are currently in.
Tools: These are your options, which you can explore later.

1.2 Basic computation in the command window


Although MATLAB can be used for writing complex functions, it can also act as a simple calculator. In
this section, you can familiarise yourself with the basic command window and its capabilities by
typing simple commands.
Arithmetic
MATLAB can perform basic operations, just like a calculator. Try typing each of these into the
command window, and hit enter after each calculation:
2+9
13-4
3*4
55/11
MATLAB will return the answer to the calculation, like so:
ans = 11
MATLAB also has built-in functions. Try some of these:
exp(4)
log(23)
sqrt(64)
abs(-3)
There are many more built-in MATLAB functions you can use when writing your own functions, but
you will learn these over time.
1.3 Variables
A core concept in programming is the use of variables. A variable is a name (a string of characters,
beginning with a letter) which is assigned a specific value using the = symbol. You can name your
variable whatever you want it wont affect the way it functions, but it is a good idea to name
important variables something that will help you remember what it is later on. Here is an example,
where the variable named a is assigned the value 4:
a = 4
Its as simple as that; just type the above code into the command window (it will return a = 4
again because we have not suppressed the output, but we will learn about that later). Now, the
variable a has the number 4 associated with it. Any time you write the letter a in the command
window, MATLAB will read it as 4 instead. For example, typing sqrt(a)will return ans = 2,
because MATLAB reads the command as sqrt(4).

You can change the number assigned to the variable a by typing something else. For example, try
a = 1
Now, MATLAB has forgotten the value 4 and replaced it with 1 instead. You can check this by
looking at the workspace.
MATLAB has a few built-in variables such as pi. Try the command cos(2*pi).
You can assign a variable name to almost anything in MATLAB, even complex functions and
commands, for example
myNum = sin(4*pi/3) + abs(2*a)
Notice that the variable myNum refers to other variables, pi and a. If you change a, the current
value of myNum will not change. You will have to re-assign the variable myNum in order to change its
value.
It is important to know that capitalisation of variables matters. mynum is not the same as myNum.
Also note that if you make a typo when calling a variable, MATLAB wont know! It will simply think
youre trying to access a variable that you have not yet defined, and give an error message.
1.4 Suppressing outputs
Until now, every time you create a new variable, MATLAB will return the value of the variable in the
command window right after youve defined it. This is known as printing the output. This doesnt
do any harm, but it is slightly unnecessary. When you write functions, you wont want MATLAB to
print hundreds of values every time it assigns a new value to a variable! In order to suppress an
output, simply type a semicolon at the end of the line. For example, try this:
x = 23;
It still stores the variable, but it doesnt parrot back its value. Remember your semicolons, and your
command window will be a much more peaceful place, with no unnecessary outputs!

2 Matrices
MATLAB, as Im sure youll hear again, is the matrix laboratory, so the majority of techniques
youve learnt so far for matrices can also be used in MATLAB.
2.1 Creating a matrix
To be able to start using those techniques, you need to tell MATLAB exactly what the matrix looks
like. Heres how to do it.
Suppose you wanted to create the matrix:
[

Then you should type the following into the workspace in MATLAB:

The A = is simply assigning the matrix to the variable name A, as we learnt earlier.
The * tells MATLAB that what youre typing is going to be a matrix. If you use a different kind of
bracket, you wont get a matrix out when you press enter.
The commas separating the numbers tell the computer that the two numbers either side of the
comma are different elements of the matrix. If you omitted the comma between the 4 and the 3,
youd get an error telling you that you didnt put the right number of elements in the matrix.
The semi colon after the 2 means that you are starting a new row of the matrix, you should do this
every time you want to start a new row, so if you want n rows in your matrix, you should have n-1
semi colons between the square brackets.
Finally, closing the square bracket means youve finished adding all of the elements to your matrix.
Now just press enter to see it displayed on the screen.
2.2 Common errors
1) Using the wrong type of bracket
2) Trying to enter objects other than numbers as elements
3) Unbalanced numbers of elements on different rows

2.3 Operations with matrices


Suppose you have two matrices, A and B, and you want to add them together. Simply type A+B and
press enter, and MATLAB will display their element-wise sum. Note that instead of creating A and B
separately, you could just create them in the same line, using the notation as above. For example if
you wanted to do the sum:
[

You could either type

Or

In exactly the same way, you can multiply two matrices together by changing the + symbol for the
* symbol. (Since MATLAB knows that the objects are matrices, it will perform matrix multiplication
in this case rather than element-wise multiplication. If you want to perform element-wise
multiplication on matrices, you must use the operation .*)
If you want to perform a certain operation to every element of a matrix A, for example add 3 to each
element, just type A+3. Or to multiply every element by 2, type A*2.
To access a certain element of a matrix, all you need to do is type the name of the matrix, and then
in round brackets immediately next to it type the row the element is on, then the column its in. The
two numbers should be separated by a comma.
So if you had the matrix
[

The 7 is on the third row, and in the 1st column so you would access it by typing B(3,1)
2.4 More advanced operations
Of course, you probably learnt to do some more difficult techniques with matrices than youve just
seen above. Below are instructions for finding the determinant, inverse and transpose of a given
matrix with the help of matlab.
Determinant: To find the determinant of a matrix A, type det(A)
Inverse: To find the inverse of a given matrix B, type inv(B)
To transpose a given matrix C, type transpose(C)

3 Functions
3.1 Creating a new function
In principle, functions in MATLAB work just like they do on paper. You enter a number, which gets
subjected to a set list of commands and then you get given a number back. Only in MATLAB, you can
apply functions to objects other than numbers, such as vectors or matrices. Heres how:
Go to Home --> New --> Function. A new window like this should open.

The blue function simply tells MATLAB that you are writing a function. Similarly, the blue 'end'
indicates the end of the function.
3.2 Output arguments
The square brackets containing the words output_args are very important this is the output
variable of your function. You will probably want to delete output_args and replace it with another
name - usually we name this variable something like out or answer. (Later you will learn to have
multiple output arguments, but for now we will just focus on one.) Like any variable, the name of the
output argument doesnt matter to MATLAB, but you might find easier to use one of the above
names, just so youre sure what it is supposed to be doing. When we use this name inside the
function, MATLAB will set (if left-hand side of =) or use (right-hand side) the value of the function.
The name has no meaning outside the function.
3.3 Naming a function
( ), etc. we need to
Just like when we use functions normally, and we use names like ( ) ( )
give each new function a name, so that MATLAB can distinguish between different functions. The
name of the function should replace the Untitled on the right hand side of the equals sign.
3.4 Input arguments
The vast majority of functions we see in MATLAB require us to give at least one input argument. An
input argument is the value (or one of the values) we enter into the function, and it gives us an
answer based on the input argument. For example, say we had a function ( )
. Then the
input argument would be
And if we call the function with the value x=5, then we would have
( )
. Sometimes, we are required to use more than one input argument, that is,

the end result depends on two different variables. To do this, all we do on the top line is insert two
variables, separated by a comma.
The number one rule with functions is if you tell MATLAB to do something to a variable, you must
either have already defined it as an input argument, or you have to have defined it in the function
itself, either as a constant, or something that depends on the input argument(s).
3.5 Commenting (Chapman 28,270)
After youve been writing functions for a while, at some point, youll have to reuse a function youve
previously written. When you do, you may find it hard to understand what you initially wrote. This
can all be avoided by explaining what you are doing as you write the function. This is done by typing
% and then typing a brief statement on what a line of text is supposed to accomplish. You can
recognise comments because the font is green, and MATLAB knows to ignore it, so you can type
anything and it wont count as part of the code. When you first start programming, you should
comment on anything apart from the blindingly obvious, as it is good practice, but as you become
more experienced youll only need to comment on more complicated parts, because youll
understand the code more.
3.6 Error Checking
It is a fundamental fact of some functions that you cant just input any old argument and expect to
get a logical answer. For example, try as we might, we cant come up with a real solution to
( ), because the function is not defined for that value. In this respect MATLAB is the
same in that some functions just wont work for some input values.
It is regarded as good programming practice to account for these undefined areas at the start of
your code, and it is referred to as error checking. The best thing we can do is just to stop the code
running as soon as we discover we have a variable that wont give a sensible answer.
Why should we do this? Well in some cases, a variable wont just give an answer or return an error,
it will carry on running on and on infinitely, which is obviously a problem. So we can stop the
function from doing this if we discover the problem early enough.
This is where if/else statements (-Chapman 213) come in handy. If we know a function wont work
for certain values, then we can issue statements before the main part of the function which stop the
function before it can run into trouble. There is an explanation of if/else statements in chapter 4,
and a guide for debugging in chapter 6, but here is an example of a function that you can come back
to later once you understand these topics.
3.7 The factorial function (Chapman 328)
This is a great opportunity for us to consolidate some of the things weve seen so far. Well do so by
looking at the factorial function (which youll see or will have already seen in JHDs lectures).

First, lets relate this to the previous subsections of this chapter. We have answer as our output
argument, so it couldnt be clearer what it means. The function has the appropriate name Factorial
(note that, as with variables, capitalisation does matter). We know that Factorial only depends on
one number, so we only need one input argument. Then we have a few lines of commenting which
make it clear what the function does, and how it does it.
After the initial comments, we have our error checking: The function checks the value of n we have
given it, and tests to see if it is a non-negative integer. In the event that n doesnt meet our
requirements, there are two ways to deal with it: the error function and a one off answer.
The one off answer (which is not the way used in the above function) is a way of pretending that
we dont mind that n is a dodgy input. If the if/else condition which checks the error is met, then we
use our output argument there and then to give an output. Usually, the output will be something
along the lines of it does not work for this value. In the Factorial function, we would see something
along the lines of
( )

Note that if we want to print words in MATLAB, we have to put quotation marks around them
The error function (seen above, also see Chapman 286 ) is perhaps the slicker way of dealing with
the problem, as at some point in your MATLAB career, youre going to have to write what are called
subfunctions (-Chapman 321-323), which are functions which have the sole purpose of assisting
another function. The great thing about the error function is if the error is picked up in the
subfunction, MATLAB still prints the error on the main screen, so you know exactly what has gone
wrong, whereas the one off answer, while avoiding an error in one place, might create a much
more confusing error somewhere else. Dont worry if this sounds confusing, it will make much more
sense once you start using subfunctions regularly.
3.8 Recursion (Chapman 328)
Perhaps the first time you looked at the last line of the code two pages ago, you were a bit confused.
Thats not a problem, because it used a technique called recursion, which youll probably have seen
in some way before, but you might not have realised it.
The last line looks like this:

Now, if someone asked you what 8! was, you probably wouldnt be able to tell them straight away,
but it wouldnt take long to work out. You know that 1!=1 and 2!=2*1! and so on until you get to
8!=8*7!=40320. This is all that the line of code above is doing. MATLAB doesnt know straight away
what Factorial(n) is as a number, but it has an equation for it. In order for MATLAB to solve that
equation it needs to know what Factorial(n-1) is, so it tries to solve the similar expression for
Factorial(n-1), but it runs into the same problem again and again until, finally, it reaches the base
case, which is a number for which we have told MATLAB the actual answer. Now, MATLAB is able to
assign a number to Factorial(1), and because it has a number for Factorial(1), it can give one to
Factorial(2), and so on, until it reaches all the way to Factorial(n).
At this point youre probably thinking how slow and laborious that process seems. If so, youre right,
it is. For us. But not for MATLAB. In fact to demonstrate how quick MATLAB is, Factorial(100), a
number which in standard form is approximately
, can be computed in less than 0.0075
seconds. The point is that recursion is usually a fast and effective way of writing a function. Other
examples you will see in the course include the Fibonacci numbers, and a method of sorting lists of
numbers called merge sort. Both conform to the same basic idea. The output is simply the function
itself, except the input argument is a smaller number (or list of numbers), and this process continues
until the function hits the base case.
*Note to the reader: Try googling recursion. If you understand the joke then you already
understand the topic!]
3.9 Global variables (Chapman 290-291)
Youve already seen how to allocate variables, and global variables are merely a way of linking up
variables in several areas. Normally, if you create a function with the variable x in it, and also

create a variable in the base workspace (on the main page) called x, then these two variables are
very much distinct, they are linked in name only. However, if you write in the base workspace
global x and the same in your function, then the variable x in the function is the variable in the
base workspace. They are identical. You can tell a variable has been globalised because it should be
displayed in a bright blue font.

4 Control Structures
4.1 If-else expressions
Using an if-else expression allows your function to follow different sets of instructions depending on
whether a condition is true or false. It is best to demonstrate using a simple example, in the context
of a function.
function [ out ] = compare( in )
if in < 3
out = Your number is less than three!;
elseif in == 3
out = Your number is equal to three!;
else
out = Your number is less than three!;
end
end
This will create a function with one input, which should be a number. The function will then tell you
whether your number is less than, more than, or equal to 3. This may not seem like a revolutionary
function, but once you understand if/else statements you will be able to use them to create much
more complicated functinos!
Now lets go through it step by step. The first word that you need to type is if. This lets MATLAB
know that youre starting to use one of its special in-built control structures. in is just our variable,
and we are comparing it to the number 3. MATLAB will only continue to the next line if in is less
than 3; otherwise it will move on to the next statement, the elseif. You can have as many
elseif statements as you want, depending on how many conditions there are, or you can have
none at all! The elseif is very similar to if (it does exactly the same thing), but you can only have
one if, and it must be at the beginning. Once again, MATLAB will compare in to 3, and if they are
equal it will continue with the next line (printing Your number is equal to three! to the command
window), but otherwise, it will move straight on to the next statement in this case, else.
Before we talk about else, notice that we used a double equals sign (==). This is different to a
single equals. A single equals is used to assign a value to something, but a double equals is used
when youre asking a question: in this case, we are asking is in equal to 3? so we use a double
equals. Your if-else structure wont work if you use = when you should be using ==, so make sure you
learn the difference!
Finally, MATLAB will look at the else condition. You dont have to have an else condition, but you
cant have more than one. MATLAB will only go to this line of code if none of the previous conditions

have been satisfied, and all cases that do not satisfy previous if or elseif statements will end up
here. If you want to cover all situations, you probably want an else; if you only want your code to
continue in a few specific situations, you might not want to use one.
End your if-else structure with an end, so MATLAB knows that youre done. It will automatically
indent your end.
4.2 For and while loops
For loops and while loops are quite similar to if-else structures, but they are used to cycle through a
number of iterations of a command.
4.2.a For loops
Here is an example of a simple for loop:
for i = 1:10
A(i)=i^2;
end
This simple script will create a row vector named A which contains the squares of the numbers 1 to
10. Lets look at it step-by-step.
As before, start your structure by typing the for command, which MATLAB will recognise as an inbuilt structure. Now, you need to define the number of times you want the loop to be repeated. The
letter i is just a counter, a kind of variable. You can name it anything, but letters like i and j are
common. Notice how we refer to this letter throughout the code. Each iteration, the value of the
variable i will change. We have set the values of i to be 1:10; this means that the value will begin at
1, then increase in intervals of 1, until it reaches the final value of 10. The value increases each time
the end statement is reached.
The middle line of code is just what we want to actually do. In this case, the command will assign the
value i2 the ith element of a row vector.
Finally, remember to place an end command at the end of the loop.
4.2.b While loops
These are used less often than for loops, but can be useful in certain situations. A while loop is very
similar to a for loop, but will continue the loop as long as a certain situation is true. Consider the
following:
while 1 < 2
A(1)=1
end

This is a very bad while loop; it will never end! The condition, 1<2, is always true, so the loop
continues infinitely, and will probably crash your computer or produce an error in MATLAB. If your
computer appears to be stuck while executing a loop, press ctrl+c to cancel the command and
prevent a crash.

Lets consider a slightly better example:


i = 1
while i<10
A(i)=i^2
i = i + 1
end
You may notice that this will do exactly the same as our example of a for loop earlier, but it required
a bit more work: first we had to define the starting place of the variable i, then the condition on it
(<10), and then we had to remember to add 1 each iteration (if you forget this, your code will run to
infinity, just like in the bad example).
It may seem like while loops are not nearly as useful as for loops, but there will be some situations
where a for loop wont work, so keep them in mind.

5 Types of object
In MATLAB there are many types of object. These objects are used to contain different things. Here
are some of them.
Type of object

What it contains

How to produce one

Double

Vector of numbers

[1,2]

Struct

Contains many fields


which can contain
char/double objects

Struct(classes,,algebra,stats-,pupils,,20,200This produces a structure that corresponds the


class algebra with 20 pupils

Cell

A cell can contain


anything in each
element is not
restricted

,cat,*1,3,5+,,2--

Char

Contains a string

cat

6 Debugging
6.1 MATLAB errors
As you write in MATLAB you will eventually come across error messages that appear when a
function or command tries to compute something outside of the boundaries of what has been
defined. Very often your functions will contain bugs (errors) that may not have been intended but
will show up in the command window as the program runs. MATLAB will often show errors in
programs by underlining the code with red lines (note that these can occasionally appear even
though the program works).
There are four main types of errors: syntax, run-time, logical and typographical. Here are a few
examples:
Syntax Error: (Parenthesis Error)
These are errors where brackets or certain characters are missing from a statement.
x = (y + 10 ) / 4)
Error: Unbalanced or unexpected parenthesis or bracket.
Run-Time Error:
These appear when an infinite loop or statement appears that MATLAB cannot compute.
1/0
ans =
Inf
Logical Error:
These are errors that occur when a program runs but the wrong answer is given.
A = [1,2,3,4,5];
A(1,6) =
Index exceeds matrix dimensions
Typographical Errors:
These errors are similar to syntax errors in the sense that they often produce the same message.
A = [1,2,3}
Error: Expression or statement is incorrect or possibly unbalanced.
6.2 Debugging steps
Debugging involves looking for the bugs that cause your program to malfunction and display an error
message. This can involve running the program line-by-line or by pointing out exactly where the
error has occurred.

A simple step in debugging is to output each variable after a logical statement by not supressing the
output with semi-colons. Another approach is to use breakpoints that make the program stop on
the line of code that has caused the error. This is often very effective as mistakes are most
commonly typographical. To access these tools we use the editor tab when editing a program.

6.3 Presentation of code: indentation/commenting style


When programming, the presentation of code is very important when it comes to assessors or even
yourself re-reading code. Comments made using the % key are important in describing what a piece
of code is trying to do and how it does it. It is very easy to forget what complex code computes after
not looking at it for some time!
Comments:
These should be very concise and straight to the point with no unnecessary points such as:
%The variable L shows length of vector A.
A = [1,2,3];
L = length(A)
L =
3
They should be specific to the commands given and not to clutter up code:
%Loop adds one to the count variable sum each iteration.
sum = 0;
for i = 1:10
sum = sum + 1;
end

Indentation:
Code can be quickly neatened up and indented by selecting all code and then pressing ctrl-I. This
lines up all if-end, for-end etc. statements appropriately so that code can run smoothly and looks
neat.
6.4 Timing for efficiency
Efficiency is very important in programming as it determines how expensive an algorithm will be to
use by checking the number of elementary operations (elops) used in a program. These are
operations or logical connectives such as +,-,*,/,<,>,== etc. These will play a big part in the type of
algorithm you should use for a function.
6.5 Error checking in your own functions
In your own algorithms you may want to check for errors yourself in cases where an algorithm will
not run properly. For example when dividing by zero or using non integer values as inputs. One way
to do this is using the error command. This involves typing error(string) with your message
represented by the string of characters inside the brackets. For example:
if y == 0
error(Cannot divide by zero);
end

7 Appendix
7.1 Crib sheet

Trig functions

Fundamental

Function
cos
sin
tan
exp
cosh
abs
sqrt
rem
fix
floor
ceil
round

Vector functions

all

any

max
mean
median
min
prod
std
sum
length
size
det
Functions

If

Description
Give cos radians
Give sin radians
Give tan radians
Gives ex
Gives cosh
Gives absolute
value
Gives square root
Gives remainder
Rounds towards 0
Rounds down to
nearest integer
Rounds up to the
nearest integer
Rounds towards the
nearest integer
Gives 1 if all
elements are nonzero
Gives 1 if any
elements are nonzero
Gives max value of
a vector
Gives mean value of
a vector
Gives median value
of a vector
Gives min value of a
vector
Gives the product of
all the elements
Gives the standard
deviation of a set
Gives the sum of
the vector
Gives the length of
the vector
Gives the size of the
vector
Finds the matrix
determinant

Example
cos(pi/2)=0
sin(pi/2)=1
tan(pi/4)=1
e0=1
abs(-3)=3
sqrt(49)=7
rem(11,2)=1
fix(9.9999)=9
floor(4.7)=4
ceil(1.1)=2
round(6.7)=7
all([1,2,3,0])=0

any([1,2,3,0])=1

max([3,7,1,2,4])=7
mean([1,2,3,4,5])=3
median([2,3,4,7,8])=4
min([2,3,4,7,8])=2
prod([1,2,3,2])=12
std([2,3,4,5])=1.290
sum([2,4,6,1])=13
length([2,4,6,3,6,7])=7
size([2,4,3,2],2)=4
det([2,1;1,2])=3
if n == 0
error(Error)
end

while
for
return

break

fprintf
zeros
isempty

Used to break out


of a function or
loop prematurely
Terminates the
execution of a for or
while loop
Formats the output
in specific ways
Create an m*n
matrix of zeroes
Returns TRUE if a
matrix is empty and
FALSE if not

while t<3
a = a + b;
end
for i=1:3
A(i)=i^2
end
return

break

fprintf(formatstr,arg1,)
zeros(m,n)
isempty(A)

7.2 Other resources

MathWorks tutorials for MATLAB: http://www.mathworks.co.uk/help/matlab/gettingstarted-with-matlab.html?s_tid=doc_12b


Codecademy tutorials for programming: http://www.codecademy.com/

You might also like