Matlab Chapter1
Matlab Chapter1
Matlab Chapter1
Performing calculations in
MATLAB
In this chapter we'll learn how to perform calculations with MATLAB. First
we'll learn how to use it as a sort of advanced calculator. Next we'll see how
to use it to perform some linear algebra calculations. Then we'll take a look at
how to use it for some simple stochastic simulations. We'll be able to do quite
a lot with only a very little MATLAB knowledge.
While you are a student at King's you can obtain MATLAB using the following
link https://internal.kcl.ac.uk/it/software/matlab.aspx.
When you rst open MATLAB the screen should look something like the schematic
diagram shown in Figure 1.1:
The main part of the screen to focus on is the so-called Command Win-
dow. This is where you type commands that you want MATLAB to act on
immediately.
For example you can enter the command:
a = 3
and MATLAB will create a variable called a and assign it the value 3. It will
also print out a message to indicate what it has done. In this case it simply
reports that a = 3.
1
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 2
b =2
a + b
a = b + 25
a = a + 1
This is how you say add one to the variable a in the MATLAB language.
Naturally you are not restricted to adding numbers. You can use * to multi-
ply numbers, / to divide them, - to substract them, ^ to raise one to the power
of another. In addition you can use brackets to group terms together.
You can also use the standard functions that you might expect such as sin,
cos, sqrt, exp log. You should use brackets when you call a function. Here's
an example:
sin ( 360 )
ans =
0.9589
1.2 Exercises
Experiment with the MATLAB command window to answer the following ques-
tions
6) Use the up arrow to run the command a=a+1 repeatedly. Check that it is
doing what you expect.
7) Work out how to compute 10 factorial using the help if you can't guess.
The name MATLAB actually stands for Matrix laboratory and not Maths
laboratory. So you might expect it makes working with matrices very easy.
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 4
a = [ 2 4 5 ; -3 1 7 ; 4 9 2 ]
Note that spaces are used to separate columns and semi-colons are used to
separate the rows. If you aren't sure what a semi-colon is, see table 1.1
So we can create two 1×3 row vectors v1 and v2 as follows:
v1 = [ 1 2 3 ]
v2 = [ 4 5 6 ]
w1 = [1; 2; 3 ]
w2 = [4; 5; 6 ]
a * w1
w1 + w2
The operators - and ^ work as you expect too. For example you can use ^2 to
square a matrix.
What about division? Well division of matrices isn't a standard mathemati-
cal operation, so you can't simply divide matrices. However, to invert a matrix
you can use the function inv (raising it to the power −1 works too, but may
be slower and less accurate since the function inv will have been optimized for
computing inverses).
MATLAB uses the division operator \ for solving matrix equations - which is
the matrix analog of division. But since matrix multiplication is non-commutative
MATLAB makes a distinction between between dividing matrices on the right
and dividing on the left. For example, suppose we want to solve the matrix
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 5
v1 '
It is quite normal to create column vectors by creating a row vector and then
taking its transpose. Here is how we could have initialized the vectors w1 and
w2:
w1 = [1 2 3 ] '
w2 = [4 5 6 ] '
As you have probably already found, entering a matrix by hand is quite a boring
task. So MATLAB provides several functions to quickly create matrices with
given values. Here are some functions that we will use a lot:
You use all of these functions in similar ways. To 4×6 matrix of zeros you
would type:
zeros (4 ,6)
To create a 3×5 matrix of random numbers between 0 and 1 you would type:
rand (3 ,5)
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 6
Symbol Term
As a shortcut, MATLAB allows you to pass only one parameter if you want
to create square matrices. For example:
zeros (4)
eye. This creates an identity matrix. This will always be a square matrix,
so you only pass in one parameter. For example eye(5) creates the 5×5
matrix. Notice that the name of this function is a pun. The word eye is
pronounced the same as the letter I.
Creating evenly spaced vectors is also a very common task. One way to do
this is to use the special colon operator :.
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 7
1:100
20:50
You can also specify the step size. For example, for the numbers between 20
and 50 going up in steps of 3 type
20:3:50
< start value >: < step size >: < end value >
Note that the above box doesn't contain real code, you are meant to replace the
text in angle brackets with your choice of variables and numbers. We'll use this
notation without comment from now on.
linspace.
One other way to create evenly spaced vectors is to use the function
For example linspace(30,70,10) creates a vector containing 10 elements evenly
spaced between 30 and 70. Whether you use the colon operator or linspace
simply depends on whether you want to specify the number of steps or the step
size.
Suppose that dollarPrices contains the stock price (in dollars) for the ACME
corporation for every day in the last week and thatr contains the USD to GBP
exchange rate for every day in the last week:
then to compute the stock price for ACME in GBP for every day in the last
week, we want to multiply together the vectors s and r cell by cell. We do this
using the operator .*. That is a star with a dot in front.
At the start of this tutorial we used short variable names like a and b. We've
now started using longer names like gbpToUsdRates.
Variable names in MATLAB should not contain spaces and should not begin
with numbers but otherwise they can be a mix of numbers and letters. MATLAB
is case sensitive, so the variables a and A are dierent. The fact that you can't
use spaces isn't much of a problem, just use camel case (starting new words
with a capital letter). Its called camel case because the words have humps like
camels.
In mathematics it is conventional to use single letter variable names to the
extent that mathematicians borrow letters from Greek and Hebrew to make their
formulae shorter. In computing longer names are preferred. The big advantage
of longer names is that it is much easier to understand what is going on when you
look at code with long variable names. The code: gbpToUsdRates = dollar-
Prices .* gbpToUsdRates is pretty self explanatory. I strongly recommend
using long variable names.
When you think of a matrix as being a matrix of data rather than a linear
transformation, there are various statistical functions you might want to apply
to the matrix: sum, mean, std, median, prctile all work in a similar way. For
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 9
example sum(v) computes the sum of the elements in a vector or the sum of the
columns of a matrix.
The function std computes the standard deviation of a vector. By default
it computes the sample standard deviation, but you can get it to compute the
population standard devation if you want - see the online help.
The function prctile computes a given percentile of a vector of data.
size which tells you the dimensions of the
Another very useful function is
vector or array andlength which tells you the largest dimension.
The function hist plots a histogram of a vector of data. For example, recall
that the function randn generates normally distributed random numbers. So
the following code will plot a histogram of a random sample of ten thousand
numbers from the normal distribution:
There are two things you probably won't like about this - rstly the his-
togram doesn't contain very many bars so it doesn't look as normally distributed
as you might like and secondly it isn't very helpful to print out the array of ten
thousand numbers. Here is how you x those issues:
We have added a semi-colon on the end of the rst line. It means don't print
the result.
On the second line we have passed in an extra parameter of 100, this is the
number of bars to show in the histogram.
We can combine all of these ideas to perform some quite sophisticated calcula-
tions.
1 + 2 + 22 + 23 + 24 + . . . + 210
Solution: We rst create a vector of the numbers 0 through 10. We then use
the .^ operator to compute the associated powers of 2 and store the result in
powers. We then compute the sum.
CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 10
x = 0:10;
powers = 2.^ x ;
sum ( powers )
You could do this all in one line if you wanted: sum( 2.^(0:10) ) but it is
usually easier to understand code that has been broken into small pieces.
1.5 Exercises
4
1) What is √1 (1 + i) ?
2
2) What is the 95-th percentile of the normal distribution (with mean 0 and
standard deviation 1)? Answer this question approximately by creating a large
sample of normally distributed random numbers and then nding the 95th per-
centile.
3) How would you create a vector containing the rst 50 odd integers in MAT-
LAB? What is the sum of the rst 50 odd integers?
4) How would you create a vector of the cubes of the rst 50 odd integers in
MATLAB?
x1 + 2x2 + 3x3 = 5
−2x1 + 3x2 + 4x3 = 6
1x1 + 3x2 + 2x3 = 7
Solve the same equations using the \ and / operators. MATLAB will use Gaus-
sian elimination if you use the division operators, but will compute the matrix
inverse if you use inv. These are two quite dierent algorithms for solving linear
equations. Which is more ecient?
9) Use the documentation to nd out how to use the function randi. Suppose
that 100 dice are thrown and the numbers on the dice are added. Use randi
to simulate throwing all 100 dice 10000 times and plot a histogram of the sum.
What do you expect the histogram should look like and why?
The rst three chapters of these notes are all about using MATLAB and cover
everything needed for the course.
If you are struggling with MATLAB you could try MATLAB demystied
[2].
MATLAB have many online resources you can use to learn MATLAB and
develop your knowledge further [1].
1.7 Summary
Bibliography