An Introduction to MATLAB Version 1.1 Department of Mathematical Sciences, University of Bath0 Introduction0.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 you’ve 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 [email protected].
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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 won’t affect the way it functions, but it is a good idea to nameimportant 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
It’s 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,
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 won’t know! It will simply think
you’re 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 you’ve defined it. This is known as “printing” the output. This doesn’t
do any harm, but it is slightly unnecessary. When you write functions, you won’t want MATLAB to
print hundreds of values every time it assigns a new value to a variable! In order to suppress anoutput, simply type a semicolon at the end of the line. For example, try this:
x = 23;
It still stores the variable, but it doesn’t parrot back its value. Remember your semicolons, and your
command window will be a much more peaceful place, with no unnecessary outputs!
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. Here’s 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 doesn’t matter to MATLAB, but you might find easier to use one of the above
names, just so you’re 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
Just like when we use functions normally, and we use names like () ()(), etc. we need to
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 you’ve been writing functions for a while, at some point, you’ll have to reuse a function you’ve
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 won’t 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 becomemore experienced you’ll only need to comment on more complicated parts , because you’ll
understand the code more.
3.6 Error Checking
It is a fundamental fact of some functions that you can’t just input any old argument and expect to
get a logical answer. For example, try as we might, we can’t 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 won’t 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 won’t give a sensible answer.
Why should we do this? Well in some cases, a variable won’t 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 won’t 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 we’ve seen so far. We’ll do so by
looking at the factorial function (which you’ll see or will have already seen in JHD’s lectures).
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, you’re 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. Don’t 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.
That’s not a problem, because it used a technique called recursion, which you’ll 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 wouldn’t be able to tell them straight away,
but it wouldn’t 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 does n’t know straight away
what Factorial(n) is as a number, but it has an equation for it. In order for MATLAB to solve thatequation 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 you’re probably thinking how slow and laborious that process seems. If so, you’re 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. Otherexamples 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)
You’ve 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 < 3out = ‘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 let’s go through it step by step. The first word that you need to type is if. This lets MATLAB
know that you’re 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 areequal 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 you’re asking a question: in this case, we are asking “is in equal to 3?” so we use a double
equals. Your if-else structure won’t 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 don’t have to have an else condition, but youcan’t 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 you’re 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. Let’s look at it step-by-step.
As before, start your structure by typing the for command, which MATLAB will recognise as an in-
built structure. Now, you need to define the number of times you want the loop to be repeated. Theletter 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 i
th 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
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 wayto 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: