SlideShare a Scribd company logo
4
Most read
12
Most read
ELEC6021 Research Methods assignment:
Matlab
This assignment forms your assessment for the “Introduction to Matlab” part of
ELEC6021 Research Methods and contributes 25% of your mark for that course.
You are required to work entirely on your own and produce a write-up, which
only needs to include the Matlab code, flow charts, results and discussions that
are directly requested in the bold paragraphs below. Since this assignment is
worth five credits, it should take you up to 50 hours to complete it. Please do not
spend any more time than this since I’m sure you have better things to be doing!
You need to submit your write-up electronically at C-BASS
https://handin.ecs.soton.ac.uk/handin/0910/ELEC6021/1/
before 4pm on Thursday 12/11/2009. You also need to print out your write-up,
staple or bind it together with your C-BASS receipt and submit it at the ECS
reception before the same deadline.
Here is some advice for completing this assignment:
• The three exercises are in no particular order. You may find it easier to
complete the exercises in an order other than 1, 2, 3. For this reason, you
should read through all of this document before deciding which exercise to
tackle first.
• If you get stuck on a particular exercise, you should leave it for a while and
move on to another one. This is a better use of your time and you might
learn something in the new exercise that helps you to get unstuck in the
other one. In the event that you run out of time, it would be better to have
done quite well in all exercises rather than really well in one, but badly in
the others.
• Try to make your Matlab code as reusable, elegant, efficient, structured and
human readable as possible because marks are awarded for this. You should
include useful, concise and relevant comments in your code to help explain
1
brought to you by CORE
View metadata, citation and similar papers at core.ac.uk
provided by EdShare
its non-trivial features. The variable names you choose should either corre-
spond to the ones used in this document or should be descriptive, concise
and relevant. You should also include adequate error checking in your Mat-
lab functions to ensure that their input arguments are valid.
• Make sure that your flow charts and results clearly show what they are in-
tended to. For example, remember to annotate the axes of your plots.
• More advice is offered for each of the individual exercises below.
• Have fun!
Rob Maunder
rm@ecs.soton.ac.uk
2
Exercise 1
The values of N unknown variables x1, x2, x3, . . . , xN can be obtained by solving
the following set of N simultaneous equations, in which all other values are known
constants.
a11x1 + a12x2 + a13x3 + · · · + a1N xN = b1
a21x1 + a22x2 + a23x3 + · · · + a2N xN = b2
a31x1 + a32x2 + a33x3 + · · · + a3N xN = b3
.
.
.
.
.
.
.
.
.
...
.
.
.
.
.
.
aN1x1 + aN2x2 + aN3x3 + · · · + aNN xN = bN
These equations may be written in matrix form A · x = b as follows.






















a11 a12 a13 · · · a1N
a21 a22 a23 · · · a2N
a31 a32 a33 · · · a3N
.
.
.
.
.
.
.
.
.
...
.
.
.
aN1 aN2 aN3 · · · aNN






















| {z }
A
·






















x1
x2
x3
.
.
.
xN






















|{z}
x
=






















b1
b2
b3
.
.
.
bN






















|{z}
b
Matlab can easily solve these simultaneous equations by calculating x = A−1
· b.
However, in this exercise, you won’t have this luxury! Instead, you need to write
a Matlab function that will transform A and b into a form that makes solving the
simultaneous equations more manageable.
There are certain transformations that will maintain the relationship A · x = b
when they are simultaneously applied to both A and b. These are
• multiplying a particular row of A and b by a constant,
• adding a row of A and b to any other and
• swapping any two rows of A and b.
Using these transformations, A and b can be manipulated into upper triangular
form, becoming A′
and b′
, respectively. Here, A′
· x = b′
and all elements below
the diagonal of A′
are equal to zero.






















a′
11 a′
12 a′
13 · · · a′
1N
0 a′
22 a′
23 · · · a′
2N
0 0 a′
33 · · · a′
3N
.
.
.
.
.
.
.
.
.
...
.
.
.
0 0 0 · · · a′
NN






















| {z }
A′
·






















x1
x2
x3
.
.
.
xN






















|{z}
x
=






















b′
1
b′
2
b′
3
.
.
.
b′
N






















|{z}
b′
3
Consider the following example.
"
3 1
1 2
#
·
"
x1
x2
#
=
"
5
5
#
We can multiply the second row by -3 to obtain the following.
"
3 1
−3 −6
#
·
"
x1
x2
#
=
"
5
−15
#
The following is obtained when we add the first row to the second row.
"
3 1
0 −5
#
·
"
x1
x2
#
=
"
5
−10
#
The equation is now in upper triangular form, making it easy to solve the simulta-
neous equations and obtain the values of x1 and x2. More specifically, the second
row tells us that −5x2 = −10, giving x2 = 2. The first row reveals that 3x1 +x2 = 5.
Substituting for x2 and solving yields x1 = 1. Of course, more steps are required
when N is greater and that’s where your Matlab skills come in to play!
Draw a flow chart and write some Matlab code for a function that obtains the
upper triangular form by manipulating A and b into A′
and b′
, respectively. Your
function must also obtain the solution vector x for the simultaneous equations.
Therefore, the first line of your Matlab function is required to be as follows.
function [x, Aprime, bprime] = solve(A, b)
In cases where no errors occur, x and bprime are required to have the same di-
mensions as b, while Aprime is required to have the same dimensions as A.
Try your function with the following six tests (some of which have particular
features that will challenge your function’s error checking).
1. A =










1 1 0
2 1 1
1 2 3










, b =










3
7
14










.
2. A =















0 1 3 2
2 1 4 0
1 1 2 1
1 2 3 1















, b =















14
11
11
15















.
3. A =










1 1 3
1 1 1
2 1 1










, b =










4
2
3










.
4
4. A =
"
1 1
1 1
#
, b =
"
2
3
#
.
5. A =










1 2 0
2 0 1
0 −4 1










, b =










6
7
−5










.
6. A =















3 2 0 1
2 1 3 2
4 0 1 1
5 −2 2 1















, b =















11
21
11
11















.
Include your flow chart, a listing of your function and its responses to the
above tests in your write-up. Also, explain the particular features exhibited
by the tests that generate errors.
Here is some advice for completing this exercise:
• Begin by working out how to perform each of the three transformations
listed above in Matlab. The colon operator will be useful here.
• The six tests listed above are ordered according to how difficult it is to get
your function to respond correctly. Concentrate on getting your function to
give the correct response to the first test, before considering the second and
so on. Try solving the tests by hand so that you can see what your function
is up against!
• Draw your flow chart on a computer so that it is easy to move parts around
and make changes to it. You should be doing this in parallel with writing
your Matlab code, rather than leaving the flow chart to the end. You should
find that doing things this way will make it easier for you to break the prob-
lem down.
• Figure 1 provides a flow chart that will help you get started. Note that this
flow chart does not obtain the solution vector, it won’t work for all of the
tests listed above and it doesn’t include any error checking. Your final flow
chart will therefore have to be more sophisticated than this one.
• Not including argument checking and comments, the Matlab function can
be written using only 25 lines of code, without taking any shortcuts to cut
this down. Also, a final flow chart comprising just 20 items is possible. If
you find that your function and flow chart are much bigger than these, then
you are probably overcomplicating things.
5
j ← i + 1
by −a′
ii/a′
ji
of A′
and b′
multiply row j
of A′
and b′
to row j
add row i
j ← j + 1
A′
and b′
i ← i + 1
A and b
i ← 1
b′
← b
A′
← A
no
no
i < N − 1
j < N
yes
yes
Figure 1: Flow chart for rearranging an N by N matrix A and an N by 1 vector b
into upper triangular form, A′
and b′
, respectively. Here, a′
i j is the element of the
matrix A′
in row i and column j.
6
• Simultaneous equations have many diverse applications, including circuit
analysis, economics and optimisation.
7
Exercise 2
The mathematical function y = f(x) has one dependent variable y, but N indepen-
dent variables, which are provided in the vector x = [x1, x2, x3, . . . , xN]. Suppose
that you want to find the particular values of the independent variables x that max-
imise the value of the dependent variable y. However, consider the case where the
function is like a ‘black box’; you can input some particular values of the indepen-
dent variables x and observe the resultant value of the dependent variable y, but
you can’t see how the function is defined. Since you don’t know how the value of
y depends on those of x, you are prevented from using differentiation techniques
to find the particular values of x that maximise the value of y. In this case, the
steepest ascent optimisation algorithm comes to the rescue!
The steepest ascent optimisation algorithm is an iterative algorithm for finding the
particular values of x that maximise the value of y = f(x). This algorithm starts
with a 1 by N vector of initial values for the independent variables x0. It then
assesses the gradient of the function f(x) in the vicinity of these values x0. Note
that this gradient g0 = ∇ f(x0) has direction has well as magnitude and so g0 is
also a 1 by N vector, just like x0. The direction of the gradient g0 points ‘uphill’,
towards better values of the independent variables x, which give higher values
for y = f(x). This allows us to easily replace our initial independent variable
values x0 with new better ones x1. More specifically, we can obtain x1 according
to xi = xi−1 + δ · gi−1, where δ is a small positive constant. Furthermore, we can
iteratively repeat this process to improve upon x1 and so on. This iterative process
can be terminated when f(xi) − f(xi−1) < t, where t is another small positive
threshold constant.
The steepest ascent optimisation algorithm is exemplified in Figure 2, in which
a surface plot is provided for a function y = f1(x) of two independent variables
x = [x1, x2]. In this example, the algorithm used initial independent variable
values of x0 = [0.5, −0.9] and it ran for 25 iterations. The evolution of these
iterations is indicated using a series of linked dots, which plots yi = f1(xi) against
xi for i = 0, 1, 2, . . . , 25. As shown in Figure 2 the algorithm always progresses
‘uphill’, in the direction of the gradient gi. Furthermore, the algorithm progresses
at a rate which is proportional to the magnitude of the gradient gi, by a coefficient
equal to δ = 0.25. As a result, big hops are used when the gradient is steep, but
small hops are used when approaching the highest point of the surface plot. In this
way, the steepest ascent optimisation algorithm is able to quickly and accurately
determine the values of x that maximises the function y = f1(x).
In this exercise, you need to use Matlab to perform steepest ascent optimisation
8
−1
−0.5
0
0.5
1 −1
−0.5
0
0.5
1
0
0.5
1
1.5
finish
y
x1
x2
start
Figure 2: Example of using the steepest ascent optimisation algorithm to max-
imise y = f1(x). Here, x = [x1, x2], x0 = [0.5, −0.9] and δ = 0.25.
9
and find the independent variable values that maximise the mathematical functions
that are listed below. You will need to write a Matlab function for each of these
mathematical functions. Each of these Matlab functions is required to have a
first line like the following example, which should be used for the first of the
mathematical functions listed below, y = f1(x).
function y = f_1(x)
Here, the argument x is required to be a 1 by N vector that provides the indepen-
dent variables x = [x1, x2, x3, . . . , xN]. Furthermore, y is required to be a scalar
that returns the corresponding value of y = f1(x).
You will also need to draw a flow chart and write a Matlab function for performing
the steepest ascent optimisation algorithm. Note that your single Matlab function
is required to work for all three of the mathematical functions listed below. The
first line of your Matlab function is required to be as follows.
function [X, y] = optimise(function_name, x_0, delta)
Here, the argument function name is a function handle that allows you to specify
which of the mathematical functions listed below to optimise. More specifically,
this argument provides a string containing the name your corresponding Matlab
function. For example, this string would have a value of ’f 1’, if the mathemat-
ical function y = f1(x) was to be optimised. The argument x 0 lets you specify
the vector of initial independent variable values x0, as described above. The third
argument delta is used to provide a value for the small positive scalar δ, which
controls how far the steepest ascent algorithm will hop in each iteration. Your
optimise function is required to have two return variables. The first X should be
an M by N matrix, where M is the number of iterations that the steepest ascent
algorithm runs for. Each row of the matrix X should provide the vector of inde-
pendent variable values xi that was used in a different iteration. More specifically,
x0 should provide the first row of X, x1 should provide the second row and so on.
The second return variable y should be an M by 1 vector that provides the cor-
responding dependent variable values yi, where the first element provides y0, the
second provides y1 and so on.
Write Matlab functions for each of the following three mathematical functions
and use them as inputs to your optimise function.
1. y = f1(x),
x = [x1, x2],
x0 = [0.5, −0.9],
f1(x1, x2) = 1 − x2
1/4 − x2
2/4 − sin(−2x1 − 3x2)/2,
δ = 0.25.
10
2. y = f2(x),
x = [x1],
x0 = [220],
f2(x1) = 9.87 sin(2b(x1)) − 7.53 cos(b(x1)) − 1.5 sin(b(x1)),
b(x1) = 2π(x1 − 81)/365,
δ = 50.
3. y = f3(x),
x = [x1, x2, x3],
x0 = [0, 0, 0],
f3(x1, x2, x3) = 9x1 + 8x2 + 7x3 − 6x2
1 − 5x2
2 − 4x2
3 + 3x1x2 + 2x1x3 + x2x3,
δ = 0.1.
Include listings of your f 1, f 2 and f 3 Matlab functions in your write-up.
Also include your flow chart and a listing of your optimise function. Take
the results you obtained by passing your f 1 function to your optimise func-
tion and use Matlab to draw a 3D figure similar to Figure 2. Similarly, draw
an equivalent 2D plot for the results obtained using your f 2 function. In ad-
dition to these plots, your write-up should include the matrix X and the vector
y that you obtained by passing your f 3 function to your optimise function.
Here is some advice for completing this exercise:
• Begin by writing the Matlab functions f 1, f 2 and f 3.
• Figure 3 provides a flow chart that will help you to get started with the
optimise function. This flow chart illustrates the process for determining
the gradient of a function in the vicinity of particular values of its indepen-
dent variables. When drawing your flow chart of the optimise function,
you can use a single box to represent the process illustrated in Figure 3.
• Draw your flow chart of the optimise function on a computer so that it is
easy to move parts around and make changes to it. You should be doing this
in parallel with writing your Matlab code, rather than leaving the flow chart
to the end. You should find that doing things this way will make it easier for
you to break the problem down.
• I found that values of ǫ = 0.0001 and t = 0.0001 work well.
• You will probably find the built-in Matlab functions feval, plot, plot3,
meshgrid, surf and hold to be useful in this exercise.
11
• Not including argument checking and comments, the optimise function
can be written using only 23 lines of code, without taking any shortcuts to
cut this down. Also, a flow chart comprising just 7 items is possible, if a
single box is used to represent the process illustrated in Figure 3. If you find
that your function and flow chart are much bigger than these, then you are
probably overcomplicating things.
• You may be interested to find out that the function y = f2(x) listed above is
the equation of time. Look it up you want to find out more.
• Optimisation algorithms have many diverse applications, including trade
theory, design problems and economic decision making.
12
f and x
j ← j + 1
g
x′
j ← x′
j + ǫ
x′
← x
j ← 1
gj ← f(x′)−f(x)
ǫ
no
yes
j < N
Figure 3: Flow chart for finding the gradient g of the function f in the vicin-
ity of the particular values provided for the N independent variables x =
[x1, x2, x3, . . . , xN]. Here, gj is the jth
element in the 1 by N vector g and ǫ is
a small positive constant.
13
Exercise 3
Consider a game where a player rolls some dice1
. If more than y number of the
dice have the same value then the player gets a score of zero. Otherwise, the
player gets a score equal to the sum of the dice values. In this game, the player
gets to choose the number x of dice to roll; the more dice the player rolls, the
higher the sum of their values is likely to be, but the higher the chance of getting
more than y dice with the same value. For example, in the case where y = 2, the
x = 4 dice would get a score of 12, since no more than y = 2 of the dice
have the same value. By contrast, the x = 6 dice would get a score of
zero, since the number of dice having a value is greater than y = 2.
For each pair of x ≥ 1 and y ≥ 1 values, there is a particular expected score. For
example, in all cases where x = 1 and y ≥ 1, the expected score is 1P( )+2P( )+
3P( ) + 4P( ) + 5P( ) + 6P( ) = 3.5, where the six possible dice values all
occur with probabilities of P( ) = P( ) = P( ) = P( ) = P( ) = P( ) = 1/6.
In fact, in cases where y ≥ x, the expected score is given by 3.5x, since the
probability of getting more than y dice with the same value is zero. However,
this probability is non-zero in (the more exciting) cases where y < x and the
corresponding expected scores are much more difficult to calculate.
The expected scores can be estimated using Monte Carlo simulation. More specif-
ically, for each pairing of x ≥ 1 and y ≥ 1, you can simply play the game lots of
times and calculate the average of your scores. Of course, Matlab can simulate the
game far more quickly than you can roll dice! In this exercise, you need to draw
a flow chart and write a Matlab function for performing Monte Carlo simulation.
The first line of your Matlab function is required to be as follows.
function dice(x, y, n, file_name)
Here, the arguments x and y should accept vectors of values for x and y, respec-
tively. For each combination of these x and y values, your function should simu-
late n number of plays of the game and determine the expected score. Your code
should write the expected scores into the text file specified by the string argument
file name. The text file should use the format exemplified in Figure 4 for the
case where x=1:20 and y=1:5. Note that the expected scores provided in Fig-
ure 4 are not correct!
The described game can also be played using a pack of playing cards2
. In this
1
Each die has six sides, namely , , , , and . Each side has a value, equal to the
number of dots it has. When a die is rolled, one of its sides is randomly selected.
2
There are 52 playing cards in a pack. Each card belongs to one of the four suits, namely
14
! y
!x 1 2 3 4 5
1 3.00 3.00 3.00 3.00 3.00
2 4.88 6.00 6.00 6.00 6.00
3 4.57 8.64 9.00 9.00 9.00
4 2.71 10.48 11.87 12.00 12.00
5 0.83 10.84 14.57 14.87 15.00
6 0.06 9.82 16.53 17.86 17.99
7 0.00 7.52 17.93 20.56 20.94
8 0.00 4.63 17.90 22.83 23.84
9 0.00 2.25 16.46 24.56 26.51
10 0.00 0.73 13.74 25.56 29.23
11 0.00 0.14 11.03 25.28 31.24
12 0.00 0.01 7.36 24.39 33.14
13 0.00 0.00 4.34 22.14 33.91
14 0.00 0.00 2.00 18.82 33.66
15 0.00 0.00 0.72 15.19 32.49
16 0.00 0.00 0.16 10.70 30.71
17 0.00 0.00 0.03 7.46 27.67
18 0.00 0.00 0.00 3.96 23.75
19 0.00 0.00 0.00 2.04 19.36
20 0.00 0.00 0.00 0.67 14.66
Figure 4: Example of the format required for the output text files. Note that the
expected scores provided in this example are not correct!
15
case, the player chooses the number x of playing cards to take from the top of a
shuffled pack. If more than y number of the selected cards belong to the same suit
then the player gets a score of zero. Otherwise, the player gets a score equal to the
sum of the selected card values, where an ace has a value of 1, a two has a value
of 2, . . . , a jack has a value of 11, a queen has a value of 12 and a king has a value
of 13. For example, in the case where y = 2, the x = 4 cards 5♥ Q♦ 8♥ A♣ would
get a score of 26, since no more than y = 2 of the cards belong to the same suit.
By contrast, the x = 6 cards 5♠ 7♣ 2♦ A♣ J♦ 3♣ would get a score of zero, since
the number of clubs is greater than y = 2.
As with the dice game, draw a flow chart and write a Matlab function for perform-
ing the Monte Carlo simulation of the described card game. The first line of this
Matlab function is required to be as follows.
function cards(x, y, n, file_name)
Here, the arguments of the cards function are used in the same way as those of
the dice function. Again, your code should write the expected scores into a text
file having the format exemplified in Figure 4.
Include listings and flow charts for your two Matlab functions in your write-
up. Also include the text files obtained by the commands
dice(1:20, 1:5, 10000, ’dice.txt’)
cards(1:20, 1:5, 10000, ’cards.txt’)
For both games, identify the optimal value of x for each value of y ∈ [1, 5].
Here is some advice for completing this exercise:
• Note that when rolling x number of dice, the resultant values will all be
independent of each other. However, x number of cards taken from the top
of a shuffled pack will not be independent of each other, since the x selected
cards are guaranteed to have different combinations of suit and value. Your
cards function should efficiently consider this. You can make sure that
your solution is efficient by ensuring that the command cards(52, 13,
1, ’cards.txt’) takes only a moment to run.
hearts, diamonds, clubs and spades. Each card has one of 13 values, namely ace, two, three, four,
five, six, seven, eight, nine, ten, jack, queen and king. No two cards in a pack have the same
combination of suit and value. Therefore, there are four cards having each value in a pack and 13
cards belonging to each suit. For example, the four sixes are 6♥ , 6♦ , 6♣ and 6♠ . Similarly, the
13 diamonds are A♦ , 2♦ , 3♦ , 4♦ , 5♦ , 6♦ , 7♦ , 8♦ , 9♦ , 10♦ , J♦ , Q♦ and K♦ . When a pack is
shuffled, the order of its 52 cards is randomised.
16
• You may like to use low values for the argument n when testing your func-
tions, in order to get them to complete quickly.
• Draw your flow charts on a computer so that it is easy to move parts around
and make changes to them. You should be doing this in parallel with writ-
ing your Matlab code, rather than leaving the flow chart to the end. You
should find that doing things this way will make it easier for you to break
the problem down.
• You will probably find the built-in Matlab functions rand, ceil, mode and
fprintf to be useful in this exercise.
• Not including argument checking and comments, the cards function can
be written using only 28 lines of code, without taking any shortcuts to cut
this down. Also, a flow chart comprising just 23 items is possible for this
game. If you find that your function and flow chart are much bigger than
these, then you are probably overcomplicating things.
• Monte Carlo methods have many diverse applications, including weather
prediction, the simulation of communication schemes, 3D graphics, eco-
nomic modelling and artificial intelligence.
17

More Related Content

Similar to Assignment On Matlab (20)

PDF
Mit6 094 iap10_lec03
Tribhuwan Pant
 
PPT
Scilab for real dummies j.heikell - part 2
Scilab
 
PPTX
INTRODUCTION TO MATLAB presentation.pptx
Devaraj Chilakala
 
PPTX
EPE821_Lecture3.pptx
Ihtisham Uddin
 
PDF
ML-CheatSheet (1).pdf
KarroumAbdelmalek
 
PPTX
Mat lab workshop
Vinay Kumar
 
PPTX
COMPANION TO MATRICES SESSION II.pptx
imman gwu
 
PPTX
Mbd2
Mahmoud Hussein
 
PPTX
presentation.pptx
raghav415187
 
PPT
Introduction to MatLab programming
Damian T. Gordon
 
DOCX
B61301007 matlab documentation
Manchireddy Reddy
 
PDF
Matlab tutorial 4
Norhan Abdalla
 
PPT
Introduction to MATLAB
Damian T. Gordon
 
PPTX
1. Ch_1 SL_1_Intro to Matlab.pptx
MOHAMMAD SAYDUL ALAM
 
PDF
A MATLAB project on LCR circuits
svrohith 9
 
PDF
matlab functions
DINESH DEVIREDDY
 
PDF
Matlab lab exe
Dr. Krishna Mohbey
 
PPT
Matlab1
guest8ba004
 
PDF
jacobi method, gauss siedel for solving linear equations
Department of Telecommunications, Ministry of Communication & IT (INDIA)
 
PPTX
introduction to matlab.pptx
Dr. Thippeswamy S.
 
Mit6 094 iap10_lec03
Tribhuwan Pant
 
Scilab for real dummies j.heikell - part 2
Scilab
 
INTRODUCTION TO MATLAB presentation.pptx
Devaraj Chilakala
 
EPE821_Lecture3.pptx
Ihtisham Uddin
 
ML-CheatSheet (1).pdf
KarroumAbdelmalek
 
Mat lab workshop
Vinay Kumar
 
COMPANION TO MATRICES SESSION II.pptx
imman gwu
 
presentation.pptx
raghav415187
 
Introduction to MatLab programming
Damian T. Gordon
 
B61301007 matlab documentation
Manchireddy Reddy
 
Matlab tutorial 4
Norhan Abdalla
 
Introduction to MATLAB
Damian T. Gordon
 
1. Ch_1 SL_1_Intro to Matlab.pptx
MOHAMMAD SAYDUL ALAM
 
A MATLAB project on LCR circuits
svrohith 9
 
matlab functions
DINESH DEVIREDDY
 
Matlab lab exe
Dr. Krishna Mohbey
 
Matlab1
guest8ba004
 
jacobi method, gauss siedel for solving linear equations
Department of Telecommunications, Ministry of Communication & IT (INDIA)
 
introduction to matlab.pptx
Dr. Thippeswamy S.
 

More from Miranda Anderson (20)

PDF
UED102 STUDY SKILLS PORTF. Online assignment writing service.
Miranda Anderson
 
PDF
Master Essay Writers UK Reviews - 4 Reviews Of Masteressaywriters.Co.Uk
Miranda Anderson
 
PDF
Write My Paper For Cheap, Cheap Online. Online assignment writing service.
Miranda Anderson
 
PDF
Academic Essay Writing. Online assignment writing service.
Miranda Anderson
 
PDF
Amazing Cause And Effect Essay Examples Thatsn
Miranda Anderson
 
PDF
New Year Printables Kindergarten Writing, New
Miranda Anderson
 
PDF
Essay Importance Group Discussion Help Research Paper
Miranda Anderson
 
PDF
Where Do I See Myself In 10 Years Essay. Where Do
Miranda Anderson
 
PDF
Things To Focus On While Writing A Literary Analysis
Miranda Anderson
 
PDF
A Notepad With The Words Cause Signal Words And Ph
Miranda Anderson
 
PDF
Obesity Essay Final - Discuss How Obesity Affects The Bra
Miranda Anderson
 
PDF
Term Paper Writing Services Reviews - The First Writing Service.
Miranda Anderson
 
PDF
College Admission Essay Writing Service - Get Ac
Miranda Anderson
 
PDF
MLASamplePaper. Online assignment writing service.
Miranda Anderson
 
PDF
Unsolicited Proposal Template. Online assignment writing service.
Miranda Anderson
 
PDF
Ucas Personal Statement Examples - Pin On Teachin
Miranda Anderson
 
PDF
IELTS BAND SCORES - Mr. Einstein Pare. Online assignment writing service.
Miranda Anderson
 
PDF
Grad School Personal Statement Template Busi
Miranda Anderson
 
PDF
Mohawk Via Linen Writing Paper Natural Shade Wa
Miranda Anderson
 
PDF
How To Write A Research Introduction 10 Steps (With Pictures) Essay ...
Miranda Anderson
 
UED102 STUDY SKILLS PORTF. Online assignment writing service.
Miranda Anderson
 
Master Essay Writers UK Reviews - 4 Reviews Of Masteressaywriters.Co.Uk
Miranda Anderson
 
Write My Paper For Cheap, Cheap Online. Online assignment writing service.
Miranda Anderson
 
Academic Essay Writing. Online assignment writing service.
Miranda Anderson
 
Amazing Cause And Effect Essay Examples Thatsn
Miranda Anderson
 
New Year Printables Kindergarten Writing, New
Miranda Anderson
 
Essay Importance Group Discussion Help Research Paper
Miranda Anderson
 
Where Do I See Myself In 10 Years Essay. Where Do
Miranda Anderson
 
Things To Focus On While Writing A Literary Analysis
Miranda Anderson
 
A Notepad With The Words Cause Signal Words And Ph
Miranda Anderson
 
Obesity Essay Final - Discuss How Obesity Affects The Bra
Miranda Anderson
 
Term Paper Writing Services Reviews - The First Writing Service.
Miranda Anderson
 
College Admission Essay Writing Service - Get Ac
Miranda Anderson
 
MLASamplePaper. Online assignment writing service.
Miranda Anderson
 
Unsolicited Proposal Template. Online assignment writing service.
Miranda Anderson
 
Ucas Personal Statement Examples - Pin On Teachin
Miranda Anderson
 
IELTS BAND SCORES - Mr. Einstein Pare. Online assignment writing service.
Miranda Anderson
 
Grad School Personal Statement Template Busi
Miranda Anderson
 
Mohawk Via Linen Writing Paper Natural Shade Wa
Miranda Anderson
 
How To Write A Research Introduction 10 Steps (With Pictures) Essay ...
Miranda Anderson
 
Ad

Recently uploaded (20)

PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PPTX
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
PPTX
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PPTX
CONVULSIVE DISORDERS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
community health nursing question paper 2.pdf
Prince kumar
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
digestive system for Pharm d I year HAP
rekhapositivity
 
CONVULSIVE DISORDERS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Ad

Assignment On Matlab

  • 1. ELEC6021 Research Methods assignment: Matlab This assignment forms your assessment for the “Introduction to Matlab” part of ELEC6021 Research Methods and contributes 25% of your mark for that course. You are required to work entirely on your own and produce a write-up, which only needs to include the Matlab code, flow charts, results and discussions that are directly requested in the bold paragraphs below. Since this assignment is worth five credits, it should take you up to 50 hours to complete it. Please do not spend any more time than this since I’m sure you have better things to be doing! You need to submit your write-up electronically at C-BASS https://handin.ecs.soton.ac.uk/handin/0910/ELEC6021/1/ before 4pm on Thursday 12/11/2009. You also need to print out your write-up, staple or bind it together with your C-BASS receipt and submit it at the ECS reception before the same deadline. Here is some advice for completing this assignment: • The three exercises are in no particular order. You may find it easier to complete the exercises in an order other than 1, 2, 3. For this reason, you should read through all of this document before deciding which exercise to tackle first. • If you get stuck on a particular exercise, you should leave it for a while and move on to another one. This is a better use of your time and you might learn something in the new exercise that helps you to get unstuck in the other one. In the event that you run out of time, it would be better to have done quite well in all exercises rather than really well in one, but badly in the others. • Try to make your Matlab code as reusable, elegant, efficient, structured and human readable as possible because marks are awarded for this. You should include useful, concise and relevant comments in your code to help explain 1 brought to you by CORE View metadata, citation and similar papers at core.ac.uk provided by EdShare
  • 2. its non-trivial features. The variable names you choose should either corre- spond to the ones used in this document or should be descriptive, concise and relevant. You should also include adequate error checking in your Mat- lab functions to ensure that their input arguments are valid. • Make sure that your flow charts and results clearly show what they are in- tended to. For example, remember to annotate the axes of your plots. • More advice is offered for each of the individual exercises below. • Have fun! Rob Maunder [email protected] 2
  • 3. Exercise 1 The values of N unknown variables x1, x2, x3, . . . , xN can be obtained by solving the following set of N simultaneous equations, in which all other values are known constants. a11x1 + a12x2 + a13x3 + · · · + a1N xN = b1 a21x1 + a22x2 + a23x3 + · · · + a2N xN = b2 a31x1 + a32x2 + a33x3 + · · · + a3N xN = b3 . . . . . . . . . ... . . . . . . aN1x1 + aN2x2 + aN3x3 + · · · + aNN xN = bN These equations may be written in matrix form A · x = b as follows.                       a11 a12 a13 · · · a1N a21 a22 a23 · · · a2N a31 a32 a33 · · · a3N . . . . . . . . . ... . . . aN1 aN2 aN3 · · · aNN                       | {z } A ·                       x1 x2 x3 . . . xN                       |{z} x =                       b1 b2 b3 . . . bN                       |{z} b Matlab can easily solve these simultaneous equations by calculating x = A−1 · b. However, in this exercise, you won’t have this luxury! Instead, you need to write a Matlab function that will transform A and b into a form that makes solving the simultaneous equations more manageable. There are certain transformations that will maintain the relationship A · x = b when they are simultaneously applied to both A and b. These are • multiplying a particular row of A and b by a constant, • adding a row of A and b to any other and • swapping any two rows of A and b. Using these transformations, A and b can be manipulated into upper triangular form, becoming A′ and b′ , respectively. Here, A′ · x = b′ and all elements below the diagonal of A′ are equal to zero.                       a′ 11 a′ 12 a′ 13 · · · a′ 1N 0 a′ 22 a′ 23 · · · a′ 2N 0 0 a′ 33 · · · a′ 3N . . . . . . . . . ... . . . 0 0 0 · · · a′ NN                       | {z } A′ ·                       x1 x2 x3 . . . xN                       |{z} x =                       b′ 1 b′ 2 b′ 3 . . . b′ N                       |{z} b′ 3
  • 4. Consider the following example. " 3 1 1 2 # · " x1 x2 # = " 5 5 # We can multiply the second row by -3 to obtain the following. " 3 1 −3 −6 # · " x1 x2 # = " 5 −15 # The following is obtained when we add the first row to the second row. " 3 1 0 −5 # · " x1 x2 # = " 5 −10 # The equation is now in upper triangular form, making it easy to solve the simulta- neous equations and obtain the values of x1 and x2. More specifically, the second row tells us that −5x2 = −10, giving x2 = 2. The first row reveals that 3x1 +x2 = 5. Substituting for x2 and solving yields x1 = 1. Of course, more steps are required when N is greater and that’s where your Matlab skills come in to play! Draw a flow chart and write some Matlab code for a function that obtains the upper triangular form by manipulating A and b into A′ and b′ , respectively. Your function must also obtain the solution vector x for the simultaneous equations. Therefore, the first line of your Matlab function is required to be as follows. function [x, Aprime, bprime] = solve(A, b) In cases where no errors occur, x and bprime are required to have the same di- mensions as b, while Aprime is required to have the same dimensions as A. Try your function with the following six tests (some of which have particular features that will challenge your function’s error checking). 1. A =           1 1 0 2 1 1 1 2 3           , b =           3 7 14           . 2. A =                0 1 3 2 2 1 4 0 1 1 2 1 1 2 3 1                , b =                14 11 11 15                . 3. A =           1 1 3 1 1 1 2 1 1           , b =           4 2 3           . 4
  • 5. 4. A = " 1 1 1 1 # , b = " 2 3 # . 5. A =           1 2 0 2 0 1 0 −4 1           , b =           6 7 −5           . 6. A =                3 2 0 1 2 1 3 2 4 0 1 1 5 −2 2 1                , b =                11 21 11 11                . Include your flow chart, a listing of your function and its responses to the above tests in your write-up. Also, explain the particular features exhibited by the tests that generate errors. Here is some advice for completing this exercise: • Begin by working out how to perform each of the three transformations listed above in Matlab. The colon operator will be useful here. • The six tests listed above are ordered according to how difficult it is to get your function to respond correctly. Concentrate on getting your function to give the correct response to the first test, before considering the second and so on. Try solving the tests by hand so that you can see what your function is up against! • Draw your flow chart on a computer so that it is easy to move parts around and make changes to it. You should be doing this in parallel with writing your Matlab code, rather than leaving the flow chart to the end. You should find that doing things this way will make it easier for you to break the prob- lem down. • Figure 1 provides a flow chart that will help you get started. Note that this flow chart does not obtain the solution vector, it won’t work for all of the tests listed above and it doesn’t include any error checking. Your final flow chart will therefore have to be more sophisticated than this one. • Not including argument checking and comments, the Matlab function can be written using only 25 lines of code, without taking any shortcuts to cut this down. Also, a final flow chart comprising just 20 items is possible. If you find that your function and flow chart are much bigger than these, then you are probably overcomplicating things. 5
  • 6. j ← i + 1 by −a′ ii/a′ ji of A′ and b′ multiply row j of A′ and b′ to row j add row i j ← j + 1 A′ and b′ i ← i + 1 A and b i ← 1 b′ ← b A′ ← A no no i < N − 1 j < N yes yes Figure 1: Flow chart for rearranging an N by N matrix A and an N by 1 vector b into upper triangular form, A′ and b′ , respectively. Here, a′ i j is the element of the matrix A′ in row i and column j. 6
  • 7. • Simultaneous equations have many diverse applications, including circuit analysis, economics and optimisation. 7
  • 8. Exercise 2 The mathematical function y = f(x) has one dependent variable y, but N indepen- dent variables, which are provided in the vector x = [x1, x2, x3, . . . , xN]. Suppose that you want to find the particular values of the independent variables x that max- imise the value of the dependent variable y. However, consider the case where the function is like a ‘black box’; you can input some particular values of the indepen- dent variables x and observe the resultant value of the dependent variable y, but you can’t see how the function is defined. Since you don’t know how the value of y depends on those of x, you are prevented from using differentiation techniques to find the particular values of x that maximise the value of y. In this case, the steepest ascent optimisation algorithm comes to the rescue! The steepest ascent optimisation algorithm is an iterative algorithm for finding the particular values of x that maximise the value of y = f(x). This algorithm starts with a 1 by N vector of initial values for the independent variables x0. It then assesses the gradient of the function f(x) in the vicinity of these values x0. Note that this gradient g0 = ∇ f(x0) has direction has well as magnitude and so g0 is also a 1 by N vector, just like x0. The direction of the gradient g0 points ‘uphill’, towards better values of the independent variables x, which give higher values for y = f(x). This allows us to easily replace our initial independent variable values x0 with new better ones x1. More specifically, we can obtain x1 according to xi = xi−1 + δ · gi−1, where δ is a small positive constant. Furthermore, we can iteratively repeat this process to improve upon x1 and so on. This iterative process can be terminated when f(xi) − f(xi−1) < t, where t is another small positive threshold constant. The steepest ascent optimisation algorithm is exemplified in Figure 2, in which a surface plot is provided for a function y = f1(x) of two independent variables x = [x1, x2]. In this example, the algorithm used initial independent variable values of x0 = [0.5, −0.9] and it ran for 25 iterations. The evolution of these iterations is indicated using a series of linked dots, which plots yi = f1(xi) against xi for i = 0, 1, 2, . . . , 25. As shown in Figure 2 the algorithm always progresses ‘uphill’, in the direction of the gradient gi. Furthermore, the algorithm progresses at a rate which is proportional to the magnitude of the gradient gi, by a coefficient equal to δ = 0.25. As a result, big hops are used when the gradient is steep, but small hops are used when approaching the highest point of the surface plot. In this way, the steepest ascent optimisation algorithm is able to quickly and accurately determine the values of x that maximises the function y = f1(x). In this exercise, you need to use Matlab to perform steepest ascent optimisation 8
  • 9. −1 −0.5 0 0.5 1 −1 −0.5 0 0.5 1 0 0.5 1 1.5 finish y x1 x2 start Figure 2: Example of using the steepest ascent optimisation algorithm to max- imise y = f1(x). Here, x = [x1, x2], x0 = [0.5, −0.9] and δ = 0.25. 9
  • 10. and find the independent variable values that maximise the mathematical functions that are listed below. You will need to write a Matlab function for each of these mathematical functions. Each of these Matlab functions is required to have a first line like the following example, which should be used for the first of the mathematical functions listed below, y = f1(x). function y = f_1(x) Here, the argument x is required to be a 1 by N vector that provides the indepen- dent variables x = [x1, x2, x3, . . . , xN]. Furthermore, y is required to be a scalar that returns the corresponding value of y = f1(x). You will also need to draw a flow chart and write a Matlab function for performing the steepest ascent optimisation algorithm. Note that your single Matlab function is required to work for all three of the mathematical functions listed below. The first line of your Matlab function is required to be as follows. function [X, y] = optimise(function_name, x_0, delta) Here, the argument function name is a function handle that allows you to specify which of the mathematical functions listed below to optimise. More specifically, this argument provides a string containing the name your corresponding Matlab function. For example, this string would have a value of ’f 1’, if the mathemat- ical function y = f1(x) was to be optimised. The argument x 0 lets you specify the vector of initial independent variable values x0, as described above. The third argument delta is used to provide a value for the small positive scalar δ, which controls how far the steepest ascent algorithm will hop in each iteration. Your optimise function is required to have two return variables. The first X should be an M by N matrix, where M is the number of iterations that the steepest ascent algorithm runs for. Each row of the matrix X should provide the vector of inde- pendent variable values xi that was used in a different iteration. More specifically, x0 should provide the first row of X, x1 should provide the second row and so on. The second return variable y should be an M by 1 vector that provides the cor- responding dependent variable values yi, where the first element provides y0, the second provides y1 and so on. Write Matlab functions for each of the following three mathematical functions and use them as inputs to your optimise function. 1. y = f1(x), x = [x1, x2], x0 = [0.5, −0.9], f1(x1, x2) = 1 − x2 1/4 − x2 2/4 − sin(−2x1 − 3x2)/2, δ = 0.25. 10
  • 11. 2. y = f2(x), x = [x1], x0 = [220], f2(x1) = 9.87 sin(2b(x1)) − 7.53 cos(b(x1)) − 1.5 sin(b(x1)), b(x1) = 2π(x1 − 81)/365, δ = 50. 3. y = f3(x), x = [x1, x2, x3], x0 = [0, 0, 0], f3(x1, x2, x3) = 9x1 + 8x2 + 7x3 − 6x2 1 − 5x2 2 − 4x2 3 + 3x1x2 + 2x1x3 + x2x3, δ = 0.1. Include listings of your f 1, f 2 and f 3 Matlab functions in your write-up. Also include your flow chart and a listing of your optimise function. Take the results you obtained by passing your f 1 function to your optimise func- tion and use Matlab to draw a 3D figure similar to Figure 2. Similarly, draw an equivalent 2D plot for the results obtained using your f 2 function. In ad- dition to these plots, your write-up should include the matrix X and the vector y that you obtained by passing your f 3 function to your optimise function. Here is some advice for completing this exercise: • Begin by writing the Matlab functions f 1, f 2 and f 3. • Figure 3 provides a flow chart that will help you to get started with the optimise function. This flow chart illustrates the process for determining the gradient of a function in the vicinity of particular values of its indepen- dent variables. When drawing your flow chart of the optimise function, you can use a single box to represent the process illustrated in Figure 3. • Draw your flow chart of the optimise function on a computer so that it is easy to move parts around and make changes to it. You should be doing this in parallel with writing your Matlab code, rather than leaving the flow chart to the end. You should find that doing things this way will make it easier for you to break the problem down. • I found that values of ǫ = 0.0001 and t = 0.0001 work well. • You will probably find the built-in Matlab functions feval, plot, plot3, meshgrid, surf and hold to be useful in this exercise. 11
  • 12. • Not including argument checking and comments, the optimise function can be written using only 23 lines of code, without taking any shortcuts to cut this down. Also, a flow chart comprising just 7 items is possible, if a single box is used to represent the process illustrated in Figure 3. If you find that your function and flow chart are much bigger than these, then you are probably overcomplicating things. • You may be interested to find out that the function y = f2(x) listed above is the equation of time. Look it up you want to find out more. • Optimisation algorithms have many diverse applications, including trade theory, design problems and economic decision making. 12
  • 13. f and x j ← j + 1 g x′ j ← x′ j + ǫ x′ ← x j ← 1 gj ← f(x′)−f(x) ǫ no yes j < N Figure 3: Flow chart for finding the gradient g of the function f in the vicin- ity of the particular values provided for the N independent variables x = [x1, x2, x3, . . . , xN]. Here, gj is the jth element in the 1 by N vector g and ǫ is a small positive constant. 13
  • 14. Exercise 3 Consider a game where a player rolls some dice1 . If more than y number of the dice have the same value then the player gets a score of zero. Otherwise, the player gets a score equal to the sum of the dice values. In this game, the player gets to choose the number x of dice to roll; the more dice the player rolls, the higher the sum of their values is likely to be, but the higher the chance of getting more than y dice with the same value. For example, in the case where y = 2, the x = 4 dice would get a score of 12, since no more than y = 2 of the dice have the same value. By contrast, the x = 6 dice would get a score of zero, since the number of dice having a value is greater than y = 2. For each pair of x ≥ 1 and y ≥ 1 values, there is a particular expected score. For example, in all cases where x = 1 and y ≥ 1, the expected score is 1P( )+2P( )+ 3P( ) + 4P( ) + 5P( ) + 6P( ) = 3.5, where the six possible dice values all occur with probabilities of P( ) = P( ) = P( ) = P( ) = P( ) = P( ) = 1/6. In fact, in cases where y ≥ x, the expected score is given by 3.5x, since the probability of getting more than y dice with the same value is zero. However, this probability is non-zero in (the more exciting) cases where y < x and the corresponding expected scores are much more difficult to calculate. The expected scores can be estimated using Monte Carlo simulation. More specif- ically, for each pairing of x ≥ 1 and y ≥ 1, you can simply play the game lots of times and calculate the average of your scores. Of course, Matlab can simulate the game far more quickly than you can roll dice! In this exercise, you need to draw a flow chart and write a Matlab function for performing Monte Carlo simulation. The first line of your Matlab function is required to be as follows. function dice(x, y, n, file_name) Here, the arguments x and y should accept vectors of values for x and y, respec- tively. For each combination of these x and y values, your function should simu- late n number of plays of the game and determine the expected score. Your code should write the expected scores into the text file specified by the string argument file name. The text file should use the format exemplified in Figure 4 for the case where x=1:20 and y=1:5. Note that the expected scores provided in Fig- ure 4 are not correct! The described game can also be played using a pack of playing cards2 . In this 1 Each die has six sides, namely , , , , and . Each side has a value, equal to the number of dots it has. When a die is rolled, one of its sides is randomly selected. 2 There are 52 playing cards in a pack. Each card belongs to one of the four suits, namely 14
  • 15. ! y !x 1 2 3 4 5 1 3.00 3.00 3.00 3.00 3.00 2 4.88 6.00 6.00 6.00 6.00 3 4.57 8.64 9.00 9.00 9.00 4 2.71 10.48 11.87 12.00 12.00 5 0.83 10.84 14.57 14.87 15.00 6 0.06 9.82 16.53 17.86 17.99 7 0.00 7.52 17.93 20.56 20.94 8 0.00 4.63 17.90 22.83 23.84 9 0.00 2.25 16.46 24.56 26.51 10 0.00 0.73 13.74 25.56 29.23 11 0.00 0.14 11.03 25.28 31.24 12 0.00 0.01 7.36 24.39 33.14 13 0.00 0.00 4.34 22.14 33.91 14 0.00 0.00 2.00 18.82 33.66 15 0.00 0.00 0.72 15.19 32.49 16 0.00 0.00 0.16 10.70 30.71 17 0.00 0.00 0.03 7.46 27.67 18 0.00 0.00 0.00 3.96 23.75 19 0.00 0.00 0.00 2.04 19.36 20 0.00 0.00 0.00 0.67 14.66 Figure 4: Example of the format required for the output text files. Note that the expected scores provided in this example are not correct! 15
  • 16. case, the player chooses the number x of playing cards to take from the top of a shuffled pack. If more than y number of the selected cards belong to the same suit then the player gets a score of zero. Otherwise, the player gets a score equal to the sum of the selected card values, where an ace has a value of 1, a two has a value of 2, . . . , a jack has a value of 11, a queen has a value of 12 and a king has a value of 13. For example, in the case where y = 2, the x = 4 cards 5♥ Q♦ 8♥ A♣ would get a score of 26, since no more than y = 2 of the cards belong to the same suit. By contrast, the x = 6 cards 5♠ 7♣ 2♦ A♣ J♦ 3♣ would get a score of zero, since the number of clubs is greater than y = 2. As with the dice game, draw a flow chart and write a Matlab function for perform- ing the Monte Carlo simulation of the described card game. The first line of this Matlab function is required to be as follows. function cards(x, y, n, file_name) Here, the arguments of the cards function are used in the same way as those of the dice function. Again, your code should write the expected scores into a text file having the format exemplified in Figure 4. Include listings and flow charts for your two Matlab functions in your write- up. Also include the text files obtained by the commands dice(1:20, 1:5, 10000, ’dice.txt’) cards(1:20, 1:5, 10000, ’cards.txt’) For both games, identify the optimal value of x for each value of y ∈ [1, 5]. Here is some advice for completing this exercise: • Note that when rolling x number of dice, the resultant values will all be independent of each other. However, x number of cards taken from the top of a shuffled pack will not be independent of each other, since the x selected cards are guaranteed to have different combinations of suit and value. Your cards function should efficiently consider this. You can make sure that your solution is efficient by ensuring that the command cards(52, 13, 1, ’cards.txt’) takes only a moment to run. hearts, diamonds, clubs and spades. Each card has one of 13 values, namely ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen and king. No two cards in a pack have the same combination of suit and value. Therefore, there are four cards having each value in a pack and 13 cards belonging to each suit. For example, the four sixes are 6♥ , 6♦ , 6♣ and 6♠ . Similarly, the 13 diamonds are A♦ , 2♦ , 3♦ , 4♦ , 5♦ , 6♦ , 7♦ , 8♦ , 9♦ , 10♦ , J♦ , Q♦ and K♦ . When a pack is shuffled, the order of its 52 cards is randomised. 16
  • 17. • You may like to use low values for the argument n when testing your func- tions, in order to get them to complete quickly. • Draw your flow charts on a computer so that it is easy to move parts around and make changes to them. You should be doing this in parallel with writ- ing your Matlab code, rather than leaving the flow chart to the end. You should find that doing things this way will make it easier for you to break the problem down. • You will probably find the built-in Matlab functions rand, ceil, mode and fprintf to be useful in this exercise. • Not including argument checking and comments, the cards function can be written using only 28 lines of code, without taking any shortcuts to cut this down. Also, a flow chart comprising just 23 items is possible for this game. If you find that your function and flow chart are much bigger than these, then you are probably overcomplicating things. • Monte Carlo methods have many diverse applications, including weather prediction, the simulation of communication schemes, 3D graphics, eco- nomic modelling and artificial intelligence. 17