Вы находитесь на странице: 1из 79

# Introduction to basic programming

By Luke Bergwerff

## Lets improve this!

1

Content
3.
5.
11.
12.
29.
33.
45.
48.
62.
67.
77.

1. Introduction to algorithmics
2. Introduction to Matlab
3. General tips
4. Conditional statements
5. Basics of arrays
6. Loops
7. Basics of plotting
8. Indexing
9. Debugging
10. Full algorithms
11. Appendix

## 1. Introduction to the algortihmics

Programming is defined as creating a sequence of instructions to enable the computer to do
something. To me programming is a tool that can be used to solve a problem in many different
ways. The something used to solve a problem may vary from person to person, but also the
sequences build vary from person to person, resulting in huge amounts of possible solutions in the
form of different codes.
Although the previous may sound very abstract to you, everyone is able to learn to program. When
you program, you write algorithms. So to be able to program you need to be able to write
algorithms. Luckily everybody uses hundreds of algorithms every day without noticing. Every time
you make a decision or you process information you use an algorithm. An example of an algorithm
that a person might use to make a decision when he is offered a concert ticket for 50 euro or 2
tickets for 80 euro is shown in figure 1.1.
Algorithms can be anywhere between very short and simple and very long and complicated.
Whatever the algorithm, you can use them naturally. When Im faced with a problem that I need to
program, I always think first: How would I solve this problem as a person?. After that I will translate
the algorithm that I would use as a person into code. This course will help you train this process.
There are three steps required to go from a problem definition to a functional code that produces a
solution. At first it is best to write all these steps down so you have a good overview of the process
and can separate the different issues that might arise while designing and writing algorithms. After
you get more familiar with these steps, they can be done very quickly and it is no longer necessary to
write them down. The steps are:
1. Problem identification
Firstly the problem needs to be defined in either words and/or equations. In this step you define
what you want to solve. If a problem is very complicated, it may be a good idea to split the problem
into multiple smaller problems and solve them individually and combine them later.
2. Logic flow of the problem
An example of a logic flow is figure 1. In this step you define how you want to solve the problem, by
building a chassis for the algorithm. For this step there is no single correct solution and many people
can come up with many different valid solutions.
3. Write the algorithm
The third step is transforming the logic flow into code. The algorithm of the concert tickets example
can be written in computer code where each decision becomes a conditional statement, the check
for which friend to bring becomes a loop and the list of friends becomes a vector or a matrix. These
things are fundamental tools for any programming language. This course will train in you in the use
of these basic tools. If you master the first two steps you can apply them to any programming
language you know. In this course Matlab will be used and so the syntax (the grammar) of Matlab will
need to be applied to the problems. For this step there are also many possibilities, leading to many
pieces of different code resulting in the exact same thing.
3

No

Do I want to go?
Yes

No

No

Yes

No

Yes
No

Yes

Yes

No

Yes

## Think of all my friends;

Who wants to go
Who do I want to go with

Yes

Do I want to go alone?
No

No

## Do I have a friend that wants go

and I want to go with?
Yes

## Buy 2 tickets for 80

Figure 1.1. Example of a simplified algorithm used by a person to determine the proper response

2. Introduction to Matlab
2.1 What is Matlab?
MATLAB is a computer program to perform numerical computation, especially linear algebra
(matrices). It began as a "MATrix LABoratory" program. It has since grown well beyond these
libraries, to become a powerful tool for visualization, programming, research, engineering and
communication.
MATLAB's strengths include cutting-edge algorithms, enormous data handling abilities, and powerful
programming tools. MATLAB is not designed for symbolic computation (e.g., analytical solutions of
equations, analytical calculation of derivatives and integrals), but does include a Maple kernel for
such computations. The interface is mostly text-based, which is a rather fast, efficient and flexible
On the university Matlab can be started from the start menu:
Programs -> Engineering -> Matlab
To exit the program either use the cross to close the program or type exit or quit in the
command window.
2.2 The interface
Figure 2.1 shows the screen after Matlab starts up by default.

Toolstrip
Current folder

Workspace
Content current
folder
Command window

Command
history

Figure 2.1. Startup screen of Matlab, several parts have been specified.
5

Command window
The command window is used for executing calculations and calling functions and scripts.
Current folder
The m-files shown in the current folder can be called upon in the command window. It is also
possible to set Matlab up to use m-files outside the current folder.
Workspace
Shows all the variables currently defined.
Command history
A list of previously entered commands in the command window. Can also be accessed in the
command window with the up and down keys.
Toolstrip
The toolstrip contains many preset functionalities.
Editor
The editor is not shown upon startup by default. The editor can be used to create and change code
and save them as m-files. To open the editor type edit in the command window.
The interface is very flexible and parts can be opened, closed and moved as pleased. It also allows to
undock parts into separate windows or dock them into one.
2.3 Help function
The help function of Matlab is excellent. It can help you understand predefined functions with
detailed explanations and examples. The help function can also be used to look for functions.
If you want to know more about a function, for example exp, type help exp in the command
window for a simple explanation. For a detailed explanation with examples, type doc exp.
At the bottom of an explanation related functions are always shown. In the help for the exp function
are for example links to the functions, log and expm. These are the inverse function and a special
matrix variant of exp. It can be very handy to find new functions this way.
To look for a function it is possible to use the command lookfor with a search command. For
example, lookfor exponential. Very generic searches will yield to many results however.
Another option is by opening the help window by clicking the help button or typing doc in the
command window. You can now find all similar function grouped together. From the help window try
for example:
MATLAB -> Mathematics -> Elementary Math -> Trigonometry
The window now shows all available trigonometry functions in Matlab.
6

## 2.4 Basic operations

Whenever text is shown in courier new, for example 1 + 2 + exp(3/2), you can copy it directly
into the command window or editor. Please do so and see what the result is and try to understand
the results. Be careful with some of the signs however, sometimes Matlab makes a distinction
between similar signs. It knows multiple versions for the apostrophe () for example.
The command window can be used as a calculator:
1 + 1
3 - 2
4 * 5
5 / 6
sqrt(2)
(sqrt(9) + 3) * 2
3 ^ 2
2 ^ 3
sin(pi)
exp(2) 1
i and j are variables for complex numbers.
pi is .
exp(1) is e.
Inf is an infinitely large number.
NaN is not a number.
To clear the command window type clc.
To clear the workspace type clear.
To close all figures type close all.
To interrupt a computation, press ctrl + C while in the command window.
For long notation type format long.
To eliminate the empty line between input and output type format compact.
For more possibilities, type doc format.
2.5 Variables
Variables are essential for writing algorithms. Variables can be used to store information. After
creating a variable it shows up in the workspace. When naming variables take the following rules into
account:
- Names cant contain spaces
- Names cant contain arithmetic operators such as + and
- Names are case sensitive
- Do not name a variable the same as built-in Matlab functions. If you do, the built-in functions
cannot be called until the variable is deleted.
7

Matlab knows different classes of variables which behave differently. Here are some of the main
classes.
Scalars
A basic floating number value. Try the following commands and watch the workspace.
a = 3
b = a - 1
c = a + b
d = a/b
a = 2
e = sqrt(a) + 1
Strings
A string contains text and is shown by default in purple. To create a string use apostrophes. To fuse
multiple strings, use brackets, [].
'a = 3'
a = '4'
b = 'Hello world! '
c = ['You have ' a ' new messages' ]
Boolean
Boolean values can only have two values: true or false, 1 or 0. They are basically the results of a yes
or no question. More on this in the chapter of conditional statements.
true
false
logical(1)
logical(0)
Matrix
A matrix is a rectangular array of scalars or Boolean values. Higher dimensional matrices are also
possible in Matlab. Note that in matrices the data type of all values need to be the same. More on
matrices in a later chapter. Matrices can be generated with brackets, [].
A = [1 2 3; 4 5 6; 9 8 7]
Cell array
A cell array is a rectangular array of mixed data. Though the content is more flexible, the
mathematical advantages of matrices are not applicable on cell arrays. It is also possible to put a cell
array in an element of another cell array. Cell arrays can be generated with braces, {}.
B = {1 2 3 4; 'Hello' false [1 2 3; 4 5 6] {1 2 3; 4 5 6}}
8

## 2.6 Scripts and functions

For more complicated tasks it is better to have the commands written and saved in a file that is
executed instead of writing in the command window. If the editor is already open you can work in it
and save your progress. Alternatively, you can type edit myfunc in the command window and a
file called myfunc will be created in the current folder. Matlab saves code as m-files with the
extension .m. The same naming rules as variables apply to scripts and functions.
Script
You can type in the editor the same way as in the command window. This is called a script. When the
script is called from the command window all the lines will be executed in order. To suppress
intermediate outputs in a script, end lines with a semicolon (;).
Function
A more complex program cannot be written with a script. By defining functions, you can create
modular blocks of code that are easily called. You can tell Matlab to make a function by making the
first line in the editor the following:
function output = functionname(input)

Note that the function name needs to be the same as the file name. Also note that the word function
turns blue as it is a Matlab keyword. Both the output and the input can be a single variable, omitted
or have multiple inputs. Multiple outputs need to be bracketed.
One big difference between scripts and functions is that scripts work with the global workspace while
functions work with a private workspace. Inside the function only the input variables and everything
defined within the function itself are known. As soon as the function ends, this private workspace is
deleted and only the defined output is passed to the calling line.
It is possible to close functions with the keyword end, but for simple functions this is not necessary.
Example 2.1
This function is saved as example1.m and converts degrees into radians.
function output = example1(input)
output = input*pi/180;
end

Note that in the code itself the output is suppressed by a semicolon. This output is unnecessary as
the local variable is deleted when the function ends. Also simply typing example1 in the command
window or running it from the editor does not work as Matlab requires an input for the function as
defined. To run the function from the command window, type:
example1(90)

Where 90 can be replaced by any scalar input. If the output needs to be stored into a variable you
can type for example in the command window:
Example 2.2
This example has multiple outputs and is saved as example2.m. The function has two inputs and
gives the quotient and the product of the two inputs.
function [quotient,product] = example2(input1, input2)
quotient = input1 / input2;
product = input1 * input2;
end

## The function can now be called from the command window.

It also possible to call a function in another function or script in the editor.
Exercise 2.1
Create an m-file that is named my_frist_script.m. Give the script file the following lines:
'This is my first script!'
value_a = 6;
value_b = -5;
value_c = value_a + value_b

Save the file and type my_frist_script in the command window. Alternatively you can click the
run button in the toolstrip of the editor or hit F5 in the editor. Congratulations! You made your first
script.
Exercise 2.2
Write a function that has three inputs. Have the function give as output the sum of all inputs and the
sum of squared inputs.
Always check whether your code behaves as it should!
The inputs 1 -5 and 3, should give -1 and 35 as output.

10

3. General tips
In this section there are some pointers that can make your life much easier when programming.
3.1 Use the help function
Not sure about the syntax or why something is not working as it should? Use the help function.
3.2 Use the step program
Be clear to yourself what step you are working on. If you try to write code without knowing what you
want the program to do, you will not be able write the proper code. If you are ever stuck writing an
algorithm, try to identify on which of the three steps described you are working on. This will help you
to specify the task you are working on, making the problem easier to solve.
3.3 Commenting
Make a habit of when writing code, to comment important lines. If you review your code after a
month or when someone else is looking at your code it helps to understand what the code does. You
can comment with the % sign or three dots . Everything behind these signs is considered
comments and is not executed as code.
3.4 Try new stuff out
Are you wondering what something can or cannot do? Try it out! This is how you learn new stuff and
limits of functions. The quickest way to figure out what a button does, is to push it, not to study its
wirings.
What would be the result of Inf - Inf?
3.5 Test, test, test
When you write a piece of code always test whether it works properly. This becomes especially
important when writing larger codes. A mistake is made in a second, but fixing a mistake in a code
can literally cost you hours or days!
Matlab gives very specific error messages about what went wrong at what line in what file. Read the
error message thoroughly and try to figure out what caused it and how to fix it.

11

4. Conditional statements
4.1 Introduction
Conditional statements are a fundamental programming tool. Whenever a distinction between
several scenarios has to be made, a conditional statement needs to be applied. In real life conditional
statements are represented by a yes-or-no-question. Examples are:
Is this fruit red?
Do I have enough money in my wallet to buy this?
Am I going to get out of bed today?
Do I like this music?
When writing code the questions are similar:
Is x larger than 2?
Is the length of vector v shorter than 5?
Is x^2 + y^2 smaller than 1?
Is the smallest number in matrix A larger than 0?
Is this variable a scalar?
The structure for these questions is called a conditional statement. When writing code, mind the
syntax (code grammar), it is very strict. The syntax for conditional statements in Matlab is the
following:
if <condition>
disp(you can put any command here)
end

The <condition> is a Boolean value, which is basically the answer to a yes-or-no question. After
the <condition> you can put commands and the conditional statement is finished with the
statement end. These commands will only be executed if the answer to the question is yes.
4.2 Boolean values
Conditions are Boolean values, meaning that they can have two values: true (also 1) or false (also 0).
The most common one is to check whether a variable contains a certain value. Type in the command
var = 4
var == 4

## Boolean values can also be stored in a variable:

condition = var == 4

12

It is very important to note the double equal signs. The code requires a very strict syntax. var = 4
means var equals 4 and assigns a variable a value and var == 4 means Is var equal to 4? and
represents a Boolean value. Greater than and smaller than conditions are also very common.
var
var
var
var

< 4
<= 4
> 4
>= 4

Try all the above commands again after giving var the value 3 and again for the value of 5.
The relational operators can be found under the help section;
Help -> MATLAB -> Language Fundamentals -> Operators and Elementary Operations -> Relational
Operations -> Relational Operators
4.3 The syntax
Next several possible syntaxes for conditional statements will be discussed. It is essential to pay
attention to the syntax, because if a command is not written correctly it will error or even worse: do
something else than intended without notifying you. Remember that the basic shape of a conditional
statement (or if-block) is the following;
if <condition>
disp(you can put any command here)
end

The <condition> is a Boolean value and the commands between <condition> and end are
only executed if the <condition> has a Boolean value of true. A small working example is:
x = 5;
if x > 4
disp('x is larger than 4')
end

The if-block has several variants however. The first is the if-else block
if <condition>
disp(this is shown when true)
else
disp(this is shown when false)
end

If <condition> is true, the lines between the if and the else statement are executed. If
<condition> is false, the lines between the else and the end statement are executed. This is a
very handy system, because it splits your space of possibilities into two outcomes and covers all
possibilities so that they have only one output. A working example:

13

x = 4;
if x >= 4
disp('x is larger than 4 or equal to 4')
else
disp('x is smaller than 4')
end

You can now see the advantage of an if-else block over two separate if-blocks by running the
following piece of code, which is poorly written.
x = 4;
if x >= 4
disp('x is larger than 4 or equal to 4')
end
if x <= 4
disp('x is smaller than 4')
end

In this case the scenario x = 4 was covered twice. It can also happen that a certain is not covered
at all. The advantage of an if-else block is that every scenario is covered exactly once.
The if-else block can be expanded even more with elseif statements. Note that each elseif statement
needs an additional condition, but the else statement does not.
if <condition1>
disp(this is shown when condition 1 is true)
elseif <condition2>
disp(this is shown when condition 1 is false and condition 2 is
true)
elseif <condition3>
disp(this is shown when condition 1 and 2 are false and condition 3
is true)
else
disp(this is shown in all other cases)
end

Working example:
x = -0.5;
if x >= 4
disp('x is
elseif x > 0
disp('x is
elseif x <= -1
disp('x is
else
disp('x is
end

## larger than or equal to 4')

smaller than 4, but larger than 0')
smaller than or equal to -1')
smaller than or equal to 0, but larger than -1')

Try changing the value of x from this example to get all the different outputs.

14

Example 4.1
Write a function with one input and one output. If the input is larger than 3, the output equals 2
otherwise the output equals 1.
Even though the problem is simple, lets apply the 3 steps.
Step 1: Identify the problem
For input values X that are greater than 3, the output value becomes 2.
In all other scenarios the output value becomes 1.
The difference between > and >= matters in this case.
Step 2: Draw the logic flow
Once the problem is identified, the logic flow can be drawn as shown in figure 4.1.

output is 1

False

input > 3

True

output is 2

## Figure 4.1: logic flow scheme for the problem

Step 3: Write the code
Initial considerations:
- A function is required as stated in the problem
- There is one input, which will be called x
- There is one output which will be called z
After these considerations are made, the first lines in code can be written.
function z = example1(x)
end

Next the steps from the logic flow can be implemented. In this case there is a single step which is a
conditional statement. There are two possible outcomes described by a single condition. This mean
an if-else block is required.
function output = example1(x)
if x > 3
output = 2;
else
output = 1;
end
end

## When the function is written always test it!

15

Exercise 4.1
Write a function with one input and one output. If the input is smaller than or equal to -1, the output
equals 1 otherwise the output equals 2.
Test whether the following input produces the proper output
Table 4.1. A set of inputs and outputs to test your function
Input Output
-2
1
-1
1
3
2
Exercise 4.2
Write a function with one input and one output.
If the input is smaller than or equal to -2, the output equals 2
If the input has a value between -2 and 9, the output equals 1
If the input is larger than or equal to 9, the output equals 3
Test whether the following input produces the proper output
Table 4.2. A set of inputs and outputs to test your function
Input Output
-3
2
-2
2
1
1
9
3
11
3
Exercise 4.3
Write a function with one input and one output.
If the input is smaller than 3, the output equals 4
If the input has a value between 3 and 4 or is equal to 3 or 4, the output equals 1
If the input is larger than 4 and smaller than or equal to 100, the output equals 3
If the input is larger than 100 and smaller than 1000, the output equals 5
If the input is larger than or equal to 1000, the output equals 2.
Test whether the following input produces the proper output
Table 4.3. A set of inputs and outputs to test your function
Input Output
2
4
3
1
4
1
10
3
100
3
500
5
1000
2
16

Exercise 4.4
Write a function that has the year (e.g. 2011) as an input and executes the following command when
that year is not a leap year (a year with 366 days):
disp('This year is not a leap year')

and executes the following command when that year is a leap year.
disp('This year is a leap year')

Leap years are years that are divisible by 4. But every new century, when a year is divisible by 100
there is no leap year, except when the year is divisible by 400. Any year that is divisible by 400 is a
leap year.
Hint: look under the help to find a function that can tell you whether one number is divisible by
another:
Help -> MATLAB -> Language Fundamentals -> Operator and Elementary Operations
Test whether the following input produces the proper output
Table 4.4. A set of inputs and outputs to test your function
Input
Output
2002 not a leap year
2004
leap year
2010 not a leap year
2100 not a leap year
2200 not a leap year
2400
leap year
-400
leap year

17

## 4.4 Logical operators

Examples of logical operators are commands like, AND, OR, NOT, ALL, ANY, etc. Logical operators are
applied to multiple Boolean values to get a single new Boolean value. Try the following commands
with the Boolean values of table 4.5 (true and false can be typed directly into the command
window);
Table 4.5. sets of Boolean values for testing logical operators
B1
B2
true true
false true
true false
false false
B1 = true
B2 = false

## The AND operator;

The OR operator;
The NOT operator;

B1 && B2
B1 || B2
~B1

The NOT operator is an important operator. Note that var ~= 4 and ~(var == 4) give the same
result.
Table 4.6. sets of Boolean values for testing logical operators
B1
B2
B3
true true true
false false false
true false false
true false true
false true true
Try out the following commands with the values from table 6.
The ALL operator;
The ANY operator;

all([B1 B2 B3])
any([B1 B2 B3])

Mind that with multiple logical operators brackets may be required to give the right order of
calculations. Try the following commands with the values of table 4.6.
~B1 || ~B2 && B3
~(B1 || ~B2) && B3

## More on logical operations can be found under the help function:

Help -> MATLAB -> Language Fundamentals -> Operators and Elementary Operations -> Logical
Operations (->Logical Operators: Short-circuit)

18

Exercise 4.5
Write a script that defines two Boolean values B1 and B2. The script defines a single variable as
output. The output variable has the Boolean value true when at least one of the variables B1 and B2
is true, otherwise the output is false.
Dont forget to test your output.
Table 4.7. A set of inputs and outputs to test your function
B1
B2 output
true true
true
true false
true
false true
true
false false false
Exercise 4.6
Write a script that defines two Boolean values B1 and B2. The script defines a single variable as
output. The output variable has the Boolean value true only when one of the variables B1 and B2 is
true. If both are true or both are false the output should be false.
Dont forget to test your output.
Table 4.8. A set of inputs and outputs to test your function
B1
B2 output
true true
false
true false
true
false true
true
false false false
Exercise 4.7
Write a script that defines a vector B with four Boolean values. The script defines a single variable as
output. The output variable has the Boolean value true when none of the values in B is true. A vector
B = [true false false true]

## Dont forget to test your output.

Table 4.9. A set of inputs and outputs to test your function
B
output
true true true true
false
true false true false false
false false false true
false
false false false false
true

19

Example 4.2
Write a function with two inputs, x and y and a single output that depends on the inputs as shown in
figure 4.2. Mind that, as explained in the introduction, there are multiple solutions possible. One
solution is using the if-block structures to describe simple conditions. Or you can use the logical
operators to describe more complicated conditions. Whatever is best depends on the problem and
what suits you best. Just make sure cover every possibility once, so make sure you dont forget any
scenario or cover any scenario twice.

## Figure 4.2. required output for this function

Lets apply the 3 steps.
Step 1: Identify the problem
The space of possibilities is separated by the lines X = 4 and by Y = 5 for 4<=X<=10.
The difference between > and >= does not matter as long as all scenarios are covered once
Step 2: Draw the logic flow
Once the problem is identified, the logic flow can be drawn as shown in figure 4.3. To write down this
logic flow I look at figure 4.2 and think of it as a cake. Then I think what would be the easiest cut to
make with a knife? This is the line X = 4. The right part of the cut can then be separated by Y = 5.
Note that using logic operators can produce a different valid logic flow.

20

output is 3

False

Y>5

False

X<4

True

output is 1

True

output is 2

Figure 4.3. logic flow scheme for the problem displayed in figure 4.2.
Step 3: Write the code
Initial considerations:
- A function is required
- There are two inputs called x and y
- There is a single output which will be stored in the variable output
After these considerations are made, the first lines in code can be written.
function output = example2(x,y)
end

Next the steps from the logic flow can be implemented. In this case there are two steps that divide
into 3 possible outcomes. From the logic flow it can be seen that an if-elseif-else structure can be
used to cover all these possible outcomes exactly once.
function output = example2(x,y)
if x < 4
output = 1;
elseif y > 5
output = 2;
else
output = 3;
end
end

After the code is written it is crucial that it is tested. A piece of code should always behave as you
intended. To test your own conditional statements a function is available in the appendix (it can also
be downloaded from blackboard) called cond_st_plotter and can be called to check functions
written for most of the coming exercises in this chapter. Make sure that when you have the m-file
for cond_st_plotter that it is in the same folder as the function that you want to check and that
that folder is set as current working directory (in the top-middle of your matlab window).
cond_st_plotter only works when the to be checked function has two inputs and one output. If

an output is not 1, 2, 3, 4 or 5 it will plot a white area. When inputting one function into another the
@ sign is required. Save example_func2 and cond_st_plotter to your folder and type in the
command window:

cond_st_plotter(@example2)

After executing this command all open figure windows will close and figure 4.2 pops up.
21

## When using logical operators another possible solution is:

function output = example2(x,y)
if x >= 4 && y <= 5
output = 3;
elseif x >= 4 && y > 5
output = 2;
else
output = 1;
end
end

22

Exercise 4.8
For the exercises 4.8 to 4.13 write functions with two inputs, x and y and a single output that
depends on the inputs as shown in the figures in the exercises. Use the cond_st_plotter function
as shown in the example to check your solution. Try to apply the three steps. All output is in whole
numbers.

Exercise 4.9

23

Exercise 4.10

Exercise 4.11

24

Exercise 4.12

Exercise 4.13

25

Exercise 4.14
In a famous scene of the TV series Big Bang Theory Sheldon comes up with an extension of the
classical Rock, Paper, Scissors. For this exercise write a function that simulates this game. The
function has two inputs, which are the choices of the two players. Furthermore the function needs to
display the proper outcome.
Do not define a matrix with all the outcomes in your code, use conditional statements to provide the
proper output.
The five possible inputs per player are:
Scissor (1)
Lizard (2)
Paper (3)
Spock (4)
Rock (5)
The rules are the following:
Scissors cut paper
Paper covers rock
Rock crushes lizard
Lizard poisons Spock
Spock smashes scissors
Scissors decapitate lizard
Lizard eats paper
Paper disproves Spock
Spock vaporizes rock
Rock breaks scissors
Dont forget to test your output.
Table 4.10. A set of inputs and outputs to test your function
Input 1 Input 2
Outcome
2
2
Draw
5
5
Draw
1
3
Player 1 wins
5
3
Player 2 wins
1
5
Player 2 wins
4
1
Player 1 wins
2
3
Player 1 wins
5
2
Player 1 wins
2
1
Player 2 wins
2
4
Player 1 wins
4
3
Player 2 wins
5
4
Player 2 wins

26

## Example 4.3 a practical application

A function giving a solution to the quadratic equation is shown here as a practical application.

0
ax 2 + bx + c =

b b 2 4ac
x1,2 =
2a
Although the solution looks simple several specials cases need to be taken care of to prevent the
wrong output. For example, if a would be 0 the equation would reduce to a linear equation with a
different solution. Also the root in the equation can result in imaginary numbers. Luckily, Matlab can
calculate with imaginary number, but if a programming language could not deal with it, this would

## function [x1,x2] = example3(a,b,c)

if a == 0 % in case of a linear equation
if b == 0 % in case there is no x in the equation
disp('There is no solution for x')
else
x1 = -c/b; % there is only 1 solution for a linear equation
x2 = NaN;
end
else
D = b*b - 4*a*c; % calculate the discriminant
if D == 0
x1 = -b/(2*a); % there is only 1 solution if D is 0
x2 = NaN;
else % Matlab can calculate imaginary numbers
x1 = (sqrt(D)-b)/(2*a);
x2 = (-sqrt(D)-b)/(2*a); % standard solution
end
end

27

The following exercises are challenging and are meant for those who like to try. As with the previous
exercises write functions with two inputs, x and y and a single output that depends on the inputs as
shown in the figures in the exercises. Use the cond_st_plotter function as shown in the example
Challenging exercise 4.1

## Challenging exercise 4.2

Try not to define each square individually, imagine doing that for a 1000 x 1000 grid! Instead try to
describe the pattern with functions used in previous exercises.

28

5. Basics of arrays
5.1 Basics of arrays
When a loop is required, a vector or a matrix is usually involved. Before we go on to the next
fundamental programming tool, loops, a short explanation about vector and matrices is required. A
matrix is a m x n collection of numerical values and a vector is either a m x 1 or a 1 x n collection of
numeric values. They are called arrays. To generate matrices the brackets, [ and ], are used.
var = []
var = [1 2 3]
var = [1 2 3;4 5 6]
var = [1;2;3]
var = [1 2;3 4;5 6]
var1 = [1 2 3]
var2 = [4 5]
var3 = [var1 var2 9]

## Other commonly used functions to generate matrices are:

var
var
var
var
var
var
var
var
var
var

=
=
=
=
=
=
=
=
=
=

1:10
2:2:11
10:-1:1
var'
zeros(5,5)
ones(3,5)
rand(4,2)
var'
eye(3)
diag([4 6 1])

Note that for functions like ones the parentheses, ( and ), are used. Once a vector or a matrix is
generated, the data can be accessed with the parentheses as well:
var = 2:2:10
var(1)
var(2:4)

Data in row i and column j can be accessed through the command var(i,j). The colon, :, can be
used to select a whole row or column. The command magic generates a magic square where the
sum of all columns, rows and diagonals are equal and all elements are unique. It is very handy to test
out the coordinate system because every element has a different value.
var = magic(8)
var(1,1)
var(1,2)
var(2,1)
var(2,2)
var(3,:)
var(:,4)
var(:,:)

29

## Data can also be changed at a single point in a vector or a matrix.

var = 1:5
var(1) = 13
var(2) = 21
var(5) = 17
var = [var 6]
var = zeros(5,3)
var(1,1) = 1
var(1,2) = 5
var(5,5) = -10
var(3,4) = var(3,4) + 4

## 5.2 Calculating with arrays

When calculating with arrays, Matlab makes a distinction by calculating element wise in an array or
calculating with the whole array. Try the following commands.
A = [1 2 3; 4 5 6]
A + 5
3*A
sqrt(A)
A^2
That last one does not work as Matlab sees it as a matrix matrix multiplication instead of an element
wise operation. For a matrix matrix multiplication an m x n matrix is multiplied with a n x p matrix. If
the sizes do not match, the multiplication cant be executed. An example of a correct multiplication
is:
A = [1 2 3; 4 5 6]
B = [1 2;3 4; 5 6]
A*B
For element wise operations the multiplication sign, division sign and the power sign need a dot in
front of them. Note that for element wise operations between two matrices both dimensions need
to be exactly the same.
A = [1 2 3; 4 5 6]
B = [6 5 4; 3 2 1]
c = 7
A*c
A.*B
A + 7
B - A
A.^2
A/7
A./B

30

Exercise 5.1
Create a row vector that counts from 1 to 13 with step sizes of 3. Change the third value of this
vector to 6.
The result should be:
1

10

13

Exercise 5.2
Create 3 row vectors:
- One that counts from 1 to 5 with step sizes of 1
- One that counts from 1 to 9 with step sizes of 2
- One that counts from 1 to 13 with step sizes of 3
Paste these three vectors beneath each other into a matrix
The result should be:
1
1
1

2
3
4

3
5
7

4
7
10

5
9
13

Exercise 5.3
Generate the matrix magic(4).
Change the third value in the first row into 5
Change the fourth value in the second column into 9
Change the value 12 into 4 (look for the value manually for now)
The result should be:
16
5
9
4

2
11
7
9

5
10
6
15

13
8
4
1

Exercise 5.4
Generate a column vector that counts from 14 to -6 with step size of -5. Put the value 0 in front of
this vector and add the value 2 behind this vector.
The result should be:
0
14
9
4
-1
-6
2

31

## Example 5.1 a practical application

The matrix system is very efficient in Matlab and can be used to apply linear algebra. Consider a
system of linear equations.

x1 + 3 x2 5 x3 =
2
3 x1 x3 =
9
5 x1 + 0.1x2 3 x3 =
7
These equations can be converted to a vector matrix multiplication.

1 3 5 x1 2

9
3 0 1 x2 =

5 0.1 3 x3 7
Which is the following equation.

Ax = b
This equation is very easily solved in Matlab. More explanation about linear algebra in Matlab will
follow in coming courses, it is here just shown as an example.
A =
b =
x =
A*x

## [-1 3 -5; 3 0 -1; 4 0.1 -3] % define the system

[2 9 7]'
A\b
% solve the system
- b
% check the solution

32

6. Loops
6.1 Loops
Loops are a fundamental programming tool. They are a type of control flow that can condense
repetitive actions into a small piece of code. Lets take a look at the following code:
var = 11:20;
disp(var(1))
disp(var(2))
disp(var(3))
disp(var(4))
disp(var(5))
disp(var(6))
disp(var(7))
disp(var(8))
disp(var(9))
disp(var(10))

This code can be condensed in a very small piece of code as shown in the syntax section below. This
has the advantages that the code becomes easier to read (imagine what the above code would look
like with a vector with 10 million values), the code becomes efficient and that the repetitive pattern
becomes clear to people who read the code.
6.2 The syntax
For loop
A for loop is used when it is exactly known how many iterations need to be performed with a loop. In
the for-loop a variable is changed each iteration in the loop according to a row vector. The first
iteration the variable assumes the first value of the vector, the second iteration the variable will
assume the second value of the vector, etc.
for i = 11:20
disp(i)
end

or
var = 11:20;
for i = 1:length(var)
disp(var(i))
end

Please note that conventionally loops are written with the variables i and j. If you use use complex
numbers in the same code however, unexpected errors may occur because you overwrite the built in
constants i and j. To circumvent this, simply use different variables in loops.

33

While loop
A while-loop keeps looping as long its condition is true (Boolean value!). A while-loop can do more
than a for-loop does, but a for-loop is easier to set-up. For example the while-loop below does
exactly the same as the first for-loop, but the code is more bulky.
var = 1;
while var <= 10
disp(var)
var = var + 1;
end

There are situations however where you are forced to use a while-loop instead of a for-loop. This
occurs when you dont know the exact amount of iterations of the loop in advance.
The danger of a while-loop is that it can loop indefinitely, as in the following example. When that
happens, use ctrl + C while in the command window to stop the script.
var = 1;
while var <= 10
disp(var)
var = var - 1;
end

Another important command regarding loops is the command break. When executed inside a loop,
the code skips all remaining iterations, will go to the next end command of a loop and continues with
the code after the loop. This can be handy when a loop fulfilled its function and can be stopped early
to save time and memory. It can also be used to build fail safes:
var = 1;
counter = 0;
while var <= 10
disp(var)
var = var - 1;
counter = counter + 1;
if counter > 100
break
end
end

34

In the following examples it is shown how loops can be used to check each value in a vector or a
matrix and also how to modify them.
Example 6.1
Write a script that a) counts how many values are in a vector that are divisible by 4 and b) at which
position these are in the vector.
Step 1: Identify the problem
All values in the input vector need to be checked for divisibility by 4
The number of values divisible by 4 need to be counted
The position of these values need to be stored
Step 2: Draw the logic flow

Is the value
divisible by 4?

True

Store index i

False

For all
vector
indices i

## Figure 6.1. flow scheme to find values divisible by 4 in a vector

Step 3: Write the code
Initial considerations:
- A variable needs to be made to keep a track of the amount of values
- A vector needs to be used to store the location of the values
vector = 1:24;
counter = 0;
locations = [];

Following the logic flow there is a loop for all the elements in the vector and inside that loop a
conditional statement checks the divisibility by 4. The length of the vector is known, so a for loop is
easiest to set up.

35

vector = 1:24;
counter = 0;
locations = [];
for i = 1:length(vector)
if mod(vector(i),4) == 0
end
end

If an element is divisible by 4, the value of counter is increased by 1 and the value for i is stored in
the location vector. Also an output is made to show the result.
vector = 1:24;
counter = 0;
locations = [];
for i = 1:length(vector)
if mod(vector(i),4) == 0
counter = counter + 1;
locations = [locations i];
end
end
disp(['This vector contained ' num2str(counter) ' values divisible by 4 at
positions:'])
disp(locations)

## Another valid solution with a while loop is:

vector = 1:24;
i = 1;
counter = 0;
locations = [];
while i <= length(vector)
if mod(vector(i),4) == 0
counter = counter + 1;
locations = [locations i];
end
i = i + 1;
end
disp(['This vector contained ' num2str(counter) ' values divisible by 4 at
positions:'])
disp(locations)

36

Example 6.2
Write a script that defines a 5x6 matrix where all elements have the values aij = 1 + i + j. The second
row is an exception and has only values of ones: a2j = 1. The third column has values ai3 = 2i. Element
a23 has a value of 10.
Step 1: Identify the problem
A matrix has to be generated following a standard rule with some exceptions.
Step 2: Draw the logic flow
Note that here there are several options. It is possible to generate the entire matrix according to the
general rule and then overwrite exceptions. It is also possible to process all the exceptions inside the
loop with conditional statements like example 6.1. In this example the first option is chosen. The
logic flow is shown in figure 6.2.
Step 3: Write the code
Initial considerations:
- A matrix has to be initialized
- After the whole matrix is generated all exceptions are overwritten
The amount of rows and columns are known so a double for loop is used to treat each matrix
element once.
A = zeros(5,6);
[rows,cols] = size(A);
for i = 1:rows
for j = 1:cols
end
end

This setup is a standard nested loop for handling matrices, remember it well!

37

Initialize matrix

For all
row
indices i

For all
column
indices j

aij = 1 + i + j

i=2

For all
column
indices j

a2j = 1

j=3

For all
row
indices i

ai3 = 2i

a23 = 10
Figure 6.2 . flow scheme for generating the requested matrix

38

Following the logic flow from figure 2 the definition of the matrix elements is placed inside the loop
and two separate loops are defined to define the exception row and column. Inside these loops these
elements are redefined.
A = zeros(5,6);
[rows,cols] = size(A);
for i = 1:rows
for j = 1:cols
A(i,j) = 1 + i + j;
end
end
i = 2;
for j = 1:cols
A(i,j) = 1;
end
j = 3;
for i = 1:rows
A(i,j) = 2^i;
end
A(2,3) = 10

On second thought, the lines i =2 and j=3 can be moved inside the loop. Thus, the final algorithm
becomes:
A = zeros(5,6);
[rows,cols] = size(A);
for i = 1:rows
for j = 1:cols
A(i,j) = 1 + i + j;
end
end
for j = 1:cols
A(2,j) = 1;
end
for i = 1:rows
A(i,3) = 2^i;
end
A(2,3) = 10

## Run the script to check the result.

39

Some of the following exercises can easily be done with built-in functions of Matlab. The exercises
are meant to let you get used with using loops in combination with conditional statements, so try to
use loops for all the following exercises. Showing the short commands will help you understand what
some Matlab functions do and makes it also easy to check your scripts. Some functions also require
conditional statements, so think of the three steps. Always figure out what type of loop you want to
use beforehand!
Exercise 6.1
Write a script that initially defines a vector. The scripts needs to sum up all the values in a vector. Use
a loop for this script.
The vector [0 4 -4 9 -2 3], should give 10 as a result
Short command in Matlab:
sum(vector)

Exercise 6.2
Write a script that initially defines a variable and sets it to zero. The script repetitively adds a random
value between 0 and 1 (rand) to this variable, but stops when the variable becomes larger than 100.
Display the amount of iterations the loop performed.
The answer should average around 200.
Exercise 6.3
Write a script that initially defines a vector. The scripts needs to calculate the amount of negative
values in that vector by using loops.
The vector [0 4 -4 9 -2 3], should give 2 as an output
Short command in Matlab:
sum(vector<0)

Exercise 6.4
Write a script that initially defines a vector. The script needs to find the lowest value and the position
of this value in that vector by using loops.
The vector [0 4 -4 9 -2 3], should give -4 as the first output and the position, 3, as the second
output.
Short command in Matlab:
[value, position] = min(vector)

40

Exercise 6.5
Can you draw figure 6.3 without your pen leaving the paper and not drawing over already drawn
lines?

## Figure 6.3 . well known puzzle

There is a very easy way to determine whether this is possible. First count how many lines originate
from each point (an intersection between lines or the end of a single line). Next count how many
points have an odd number of lines, any point that has an odd number of lines needs to be either a
starting point or an ending point. If there are in total more than two points that are a start/end point
it is impossible to draw the figure following the rules. In the example there is one point with two
lines, three points with four lines and two points with three lines, meaning that the figure can be
drawn according to the rules.
Write a function that has a vector with the number of lines passing through each point as input and
counts how much odd numbers are in this vector. If there are more than two odd numbers the script
needs to execute
disp('This figure cannot be drawn without letting your pen leave the
paper')

## otherwise the script needs to execute

disp('This figure can be drawn without letting your pen leave the paper')

Can the following figure be drawn without lifting your pen from the paper or move over already
drawn lines? If your algorithm says it is possible, draw it.

## Figure 6.4 . input for the code of exercise 6.5

Exercise 6.6
Write a script that initially defines a vector and a variable. The variable has as initial value 0. The
script needs to calculate a single output by adding the first value of the vector to the variable and
subtracting the second value of the vector from the first variable. The third value is added and the
fourth is subtracted again, until the end of the vector is reached.
The vector [0 4 -4 9 -2 3], should give -22 as an output

41

Exercise 6.7
Write a function that has a matrix as input and counts the amount of occurrences of the value 1 in
this matrix. The number of occurrences is given as output.
The input reshape(round(0:0.15:2),7,2), should give 6 as output.
Short command in Matlab:
sum(matrix(:)==1)

Exercise 6.8
A cell array experiment was performed to determine the activity of an enzyme. Some of the data was
outside of the reliable range of the sensor however. The data of the experiment was stored in an
Matlab with the following command and change all values that are outside the range into NaN (Not a
Number). The reliable range of the sensor is between 1 and 100.

## Short command in Matlab:

CellArrayData(CellArrayData<1 | CellArrayData>100) = NaN;

Exercise 6.9
Write a function that has a matrix as input. Every value in this matrix that is larger than 10 is divided
by 2. The new matrix is then given as output.
The input reshape(2:2:24,3,4), should give the following matrix as output:
2
4
6

8
10
6

7
8
9

10
11
12

## Short command in Matlab:

matrix(matrix>10) = matrix(matrix>10)./2

42

## Example 6.3 a practical application

Chapter 8 will deal with Matlab specific code to efficiently replace loops. However, it is not always
possible to do so. One such a case is a recursive equation. In a recursive equation a value in an array
depends on the previous value. It is therefore impossible to calculate all elements at once. Consider
the following recursive equation which is an approximation for the golden ratio.

a (n)= 1+

1
a ( n 1)

a ( 0) = 1
a ( ) =
By using loops its possible to calculate this recursive approximation for n steps.

## n = 10; % number of iterations to compute

fi = (1+sqrt(5))/2; % golden ratio
fi_approx = ones(1,n); % initialize the output vector
fi_approx(1) = 1 + 1/1; % calculate a(1) manually
for i = 2:n
fi_approx(i) = 1 + 1/fi_approx(i-1); % calculate a(n)
end
disp(fi_approx(n)) % display approximated value
disp(fi_approx(n) - fi) % display difference with actual value

In this case the first value was calculated manually outside the loop because fi_approx(0) does
not exist in this case. There are other solutions to this problem, but this is the easiest solution. With
more iterations the approximation of the golden ratio becomes better.

43

The following exercises are challenging and are meant for those who like to try.
Challenging exercise 6.1
Write a function that has a square matrix as input. Next transpose the matrix by using loops to
relocate each element of the matrix individually. The transposed matrix is the output.
The input magic(4), should give the following matrix as output:
16
2
3
13

5
11
10
8

9
7
6
12

4
14
15
1

matrix'

## Challenging exercise 6.2

Write a script that initially defines a 4x5 matrix filled with random values between -300 and 100. The
script will apply the following rules every iteration to all matrix elements until all matrix elements
have a value between 0 and 1.
- If an element has a value smaller than or equal to 0, it increases by 20
- If an element has a value between 0 and 1, it is multiplied by 0.99
- If an element is larger than or equal to 1, a random value between 1 and 4 is subtracted from
the element
Display the amount of iteration it took for all elements to get a value between 0 and 1.
Challenging exercise 6.3
Write a function that has a single number as input and gives a Boolean value as output. Design your
own algorithm so that if the input is a prime number, the output is true, otherwise the output is
false.
Dont forget to test your function:
Not prime numbers: -4 -1 0 1 5.3 4 9
Prime numbers: 2 3 5 7 11 19
Short command in Matlab:
isprime(x)

44

7. Basics of plotting
7.1 Basic plotting in Matlab
Matlab has a powerful set of plotting functions which operate on time series of data stored in vector
(or matrices). The basic plotting function in Matlab is plot. Try the following commands in the
command window.
t = 0:0.4:10;
y = cos(t);
plot(t,y)
title('x-y plot of cosinus wave')
xlabel('time')
ylabel('Value')

A figure should pop with a cosine function. With the commands title, xlabel and ylabel strings
can be added to the figure.
The format of the plotted line can also be specified with plot. There are three possible inputs: the
line color, the line type and the marker type. Try the following commands.
t = 0:0.4:10;
y = cos(t);
plot(t,y)
plot(t,y,'.')
plot(t,y,'r')
plot(t,y,'--')
plot(t,y,'k:x')

## To see the possibilities type doc linespec in the command window.

7.2 Window handling
As you probably have noticed, when plot is executed twice the previous the first plot is lost. To
prevent this new windows can be opened. To open a new figure window type figure. To switch
back to a window that has already opened type figure() with the window number between the
parenthesis. To close a figure window type close, to close all figures type close all. Try the
following commands.
close all
t = 0:0.4:10;
y1 = cos(t);
y2 = t.^2;
y3 = t;
plot(t,y1)
figure
plot(t,y2)
figure
plot(t,y3)
figure(2)
plot(t,y2,'r.')

45

Sometimes it is desirable to plot multiple functions in the same window. When in the desired figure
window type hold on. Any plot command that is given in this window will now be added. Try the
following commands.
figure
t = -1:0.1:1;
y1 = t;
y2 = t.^2;
y3 = t.^3;
plot(t,y1)
hold on
plot(t,y2,'r')
plot(t,y3,'k')

Another time it is desirable to put multiple figures on one window. This can be done with the
command subplot. Try the following commands.
figure
t = -1:0.1:1;
y1 = t;
y2 = t.^2;
y3 = t.^3;
y4 = t.^4;
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
subplot(2,2,3)
plot(t,y3)
subplot(2,2,4)
plot(t,y4)

46

Exercise 7.1
Write a script that calculates the Fibonacci numbers for input 0 to 50 and plots them against their
input in the equation. Check the help function for logarithmic plots and see if you can get a good
figure.
Help -> Matlab -> Graphics -> 2-D and 3-D plots
The equation for Fibonacci numbers is:

F ( 0) = 0
F (1) = 1
F ( n=) F ( n 1) + F ( n 2 )
Exercise 7.2
An experiment was performed on a sample from time 1 to 100. During the experiment the activity of
the sample increased from 0 to 1 and the point of interest is the time where the activity is 0.5. The
old computer monitoring the experiment saved the output into an unhandy format. The data is saved
from top to bottom, but after a few data points a new column was generated every time.
Download the file Output_data.xlsx from Blackboard and load it into Matlab. Find a way to plot the
data into a single figure. Also plot the line y = 0.5 in the same figure to estimate the time of interest.

47

8. Indexing
8.1 Element selection
Conditional statements and loops are very general and basic tools and are required to program in
any language as long as you know the syntax of that language. The next subject, indexing, is Matlab
specific. When running loops Matlab is much slower that other object oriented programming
languages such as Java. With indexing however Matlab eliminates the need of many loops and makes
it easy to manage, transform and search data in the form of matrices quickly and efficiently.
In the loops chapter it was explained that an element in a vector could be accessed with vector(i)
an in a matrix with matrix(i,j). It is also possible to select multiple elements at the same time by
giving vectors as input for i and j. Try for example:
vector = 11:20
vector(1)
vector(3)
vector(1:3)
vector(2:9)
vector([2 7 3 5])
matrix = magic(5)
matrix(3,3)
matrix(3,2:4)
matrix(1:5,3)
matrix(:,3)
matrix(:,:)
matrix(1:4,:)
matrix([1 2 4],:)
matrix([1 5 3],[1 3 5])

Note that with the last example you do not get 3 elements, but a 3x3 matrix. The way to select three
elements from different rows and columns, for example (1,1), (5,3) and (3,5), is to use linear indices
which will be explained later.
A very handy command when handling vectors and matrices is the command end. With end you can
use the last element in a vector or column or row of a matrix without knowing the size of the vector
or matrix. Try the following examples:
vector = 11:20
vector(6:end)
vector(2:end)
vector(2:end-1)
matrix = magic(5)
matrix(end,end)
matrix(2:end-1,3:end)

48

Any selection can also be redefined as long as the value the selection is changed in to is either a
single number or a matrix of the same dimensions and size. When using indexing you must take two
things carefully in mind. First is the selection of the elements of a matrix you wish to handle and
second is how you wish the handle this selection.
vector = 11:20
vector(1) = 21
vector(1:3) = 31:33
vector([1 2 3 7]) = 0
vector([1 2 3 7]) = 41:44
vector(end+1) = 51
matrix = zeros(5)
matrix(2,:) = 1
matrix(:,3) = 2.^(0:4)
matrix(:,end+1) = 11:15
matrix = zeros(5)
matrix([1 3],[2 4 5]) = 1
matrix([1 3],[2 4 5]) = [1:3 ; 4:6]

## NOT possible: matrix([1 3],[2 4 5]) = 1:6

49

Exercise 8.1
Try to create the following matrices as efficiently as possible. Most exercises can be solved by loops
as well as indexing. If you find indexing difficult it is possible to write loops first and then convert
them to indexed matrices later if necessary. Remember though that indexing is much faster in
Matlab.
a)
0
1
0
0
0

0
1
0
0
0

2
2
2
2
2

0
1
0
0
0

0
1
0
0
0

1
1
1

1
1
1

1
1
1

2
2
1

2
2
1

5
5
5
5
5

5
3
3
3
5

5
3
1
3
5

5
3
3
3
5

5
5
5
5
5

b)
2
2
1

1
1
1

c)

d)
1.0000
2.0000
4.0000
8.0000
16.0000
32.0000

0.5000
0
0
0
0
0

0.2500
0
0
0
0
0

0.1250
0
0
0
0
0

0.0625
0
0
0
0
0

0.0313
0
0
0
0
0

e)
-1
-1
-1
-1
-1

-1
1
5
-1
9

-1
-1
-1
-1
-1

-1
2
6
-1
10

-1
-1
-1
-1
-1

-1
3
7
-1
11

-1
4
8
-1
12

-1
-1
-1
-1
-1

50

8.2 Indexing
In previous exercises and examples you have seen a nested loop to select each element of a matrix.
In the loops there could be one or more conditional statements to determine what happens with
which matrix element. For example:
A = magic(5);
[rows, cols] = size(A);
for i = 1:rows
for j = 1:cols
if A(i,j) <= 10
A(i,j) = 0;
end
end
end
disp(A)

With indexing this process can be simplified a lot. Another way to select elements other than filling in
their position in the matrix, is by giving a matrix of the same size containing Boolean values. This
matrix can be very easily obtained by using the matrix in a condition. For example the following lines
generate a Boolean matrix.
A = magic(5)
A <= 10

When used for indexing, every element that is true in the Boolean matrix will be selected.
A(A <= 10)

Remember that to modify the selection a single number or a matrix of the same dimensions and size
is required. The loop described before can now be condensed into the following lines.
A = magic(5);
A(A <= 10) = 0;
disp(A)

## Another example of indexing.

A = magic(5);
A(A>10) = A(A>10).*2

The following command only saves the selection of elements and throws the rest of the matrix away.
Be careful when using this, if you are also interested in the rest of the matrix.
A = magic(5);
A = A(A>10).*2

51

Example 8.1
Generate a dataset of x and y ranging from 0 to 10 with increments of 0.02. Use indexing to generate
a matrix that when plotted looks like figure 8.1 below:

## Figure 8.1. required output for example 8.1

Step 1: Identify the problem
The space of possibilities is separated by the lines X = 4 and by Y = 6 for X > 4.
The difference between > and >= does not matter as long as all scenarios are covered once
Step 2: Draw the logic flow

output is 1

False

Y>6

False

X<4

True

output is 2

True

output is 3

## Step 3: Write the code

Initial considerations:
- No function is required
- Three data sets need to be created, one for the x coordinates, one for the y coordinates and
one for the values that need to be plotted

52

After these considerations are made, the first lines in code can be written.
First the data sets for the x and y coordinates are generated:
xx = 0:0.02:10; % generate a mesh grid for plotting
yy = 0:0.02:10;
[XX YY] = meshgrid(xx,yy);

Next generate the matrix with the results is generated through indexing:
xx = 0:0.02:10; % generate a mesh grid for plotting
yy = 0:0.02:10;
[XX YY] = meshgrid(xx,yy);
ZZ = ones(size(XX));
ZZ(XX > 4 & YY > 6) = 3;
ZZ(XX <= 4) = 2;

## Then use plotting to visualize the matrix:

xx = 0:0.02:10; % generate a mesh grid for plotting
yy = 0:0.02:10;
[XX YY] = meshgrid(xx,yy);
ZZ = ones(size(XX));
ZZ(XX > 4 & YY > 6) = 3;
ZZ(XX <= 4) = 2;
imagesc(xx,yy,ZZ,'alphadata',ismember(ZZ,1:5)) % plot all correct data,
make incorrect data invisible
set(gca,'YDir','normal') % flip Y axis
axis image % sets x axis and y axis to contain the whole image
xlabel('X'); ylabel('Y') % label x axis and y axis
caxis([1 5]) % set color scale
colorbar %show the colorbar

Exercise 8.2
Download the file Template.m from blackboard and add a piece of code to generate the figures in
the following exercises. It is important to make distinction between this scenario and the one from
the conditional statement chapter. For the conditional statements functions were built. In this
chapter data sets are managed.

53

Exercise 8.3

54

Exercise 8.4

Exercise 8.5

55

8.3 Find
Sometimes it is preferable to find the coordinates of positions of values in a matrix, for this you can
use the find function. find finds all the non-zero elements in a matrix. When applying this to the
Boolean matrix the positions for all values for a certain condition can be easily found and changed.
Note that for the logical operators AND (&) and OR (|), the sign is used only once for arrays.
vector = 1:10
coords = find(vector < 5 | vector == 7)
vector(coords) = -vector(coords)
matrix = magic(5)
coords = find(matrix <= 10)
matrix(coords) = 0

## 8.4 Linear indices

Note that the find function for a matrix gives a single index and not coordinates for rows and
columns. This is because Matlab matrices are indexed in two ways: first is the row and column
subscripts and the second is this linear index. A linear index is indicated with a single number.
matrix = magic(3)
matrix(1)
matrix(2)
matrix(3:5)
matrix(8)
matrix(:)

Note that the last line can be used to easily reshape a matrix into a column vector. A tip for when
using sum, min or max. When for example sum is used on a matrix it will sum all the columns. When
you want to for example sum an entire matrix you can either use sum twice or transform the matrix
into a column vector first.
matrix = magic(5)
sum(matrix)
sum(matrix,2)
sum(sum(matrix))
sum(matrix(:))

Linear indices and row and column can easily be converted into one another with built in Matlab
functions.
matrix = magic(8)
lindex = find(matrix < 6)
[rows, cols] = ind2sub(size(matrix),lindex)

Note that as stated before when using the row and column subscripts you can select for more
elements you actually want. This can be circumvented by transforming the row and column
subscripts into linear indexes.
56

matrix = magic(8)
[rows, cols] = find(matrix < 6)
matrix(rows,cols)
lindex = sub2ind(size(matrix),rows,cols)
matrix(lindex)

## 8.5 List of matrix operations

The following commands are not often used, but it is good to know of their existence.
diag can be used to transform a vector into the diagonal of a matrix or the diagonal of a matrix into

a vector.
A = diag(1:4)
b = diag(A)
C = diag(3.*ones(1,5)) + diag(2.*ones(1,4),1) + diag(ones(1,4),-1)
rot90 can be used to turn a matrix 90 degrees
magic(4)
rot90(magic(4))
rot90(magic(4),2)
rot90(magic(4),-1)
sort can rearrange a vector or the rows or columns of a matrix so that the values are ordered from

low to high.
sort(10:-1:1)
sort(magic(5))
sort(magic(5),2)
repmat can make repeated copies of a matrix and paste them together.
repmat(1:10,4,1)
repmat([1 2; 3 4],3,4)
unique removes all double values from a matrix and will give a vector as output with all different

## values from the input matrix.

unique([1 1 1 1 2 1 1 5 5 4])
unique(repmat([1 2; 3 4],3,4))
setdiff removes all values of the second input from the first input.
setdiff(1:10,[4 5 7])
setdiff([4 5 7],1:10)
setdiff(1:6,4:8)
intersect gives all values that are in both inputs as output.
intersect(1:10,[4 5 7])
intersect(1:6,4:8)
ismember can check a matrix for the presence of multiple values and generates a Boolean matrix.
ismember(1:10,[2 3 8])
ismember(magic(4),[2 3 8 16])

57

Example 8.2
Generate the matrix rand(5) and count how many values are between 0.25 and 0.75. Using
indexing this problem can be solved very easily, making a logic flow not necessary. When writing a
larger code still requires it however, even when using indexing.
Option 1:
A = rand(5);
output = sum(A(:)>0.25 & A(:)<0.75);
display(['There are ' num2str(output) ' values between 0.25 and 0.75'])

Option 2:
A = rand(5);
output = length(find((A>0.25 & A<0.75)));
display(['There are ' num2str(output) ' values between 0.25 and 0.75'])

Exercise 8.6
Generate the matrix magic(9) and find the row and column subscripts of:
a) the numbers larger than 71
b) the numbers divisible by 9
c) the numbers larger than 71 and divisible by 9
Replace all the numbers that are true for a) but not for c) with 1
Replace all the numbers that are true for b) but not for c) with 2
Replace all the numbers that are true for c) with 0
Replace all other the numbers with -1
Exercise 8.7
Transform the matrix rand(10) into a sorted row vector called vec_a. Make a second vector, vec_b,
that increases linearly from 0 to 1 and has the same size as the first vector. Plot in the same figure
vec_a against vec_b and vec_b against vec_b.
Do this again for the matrices rand(4), rand(25) and randn(25).

58

Exercise 8.8
ezplot('1./(1+exp(1e2.*(t-0.5)))',[0 1])

When running the previous command it can be seen that the function makes a sharp change around
0.5. Indexing can be used for a quick estimation to find a point of interest. For example where the
function drops below 0.25. To do this, first generate a vector with time t with the precision required,
then generate a vector y from t with the equation above. Finally use indexing to find the time t1
where the function drops below 0.25 with 4 decimals precision in vector y.
Exercise 8.9
Write a function that has a matrix as an input and a number as an output. The output of the function
will be the amount of double values in a matrix. If a value occurs three times in the matrix it counts
as two double values, four occurrences count for three double values, etc.
The vector [1 1 1 1 2 3 2 4 2 3] gives 6 as output.
The matrix [ones(1,4); magic(4); [2 2 12 20]; 5:5:20; [3 9 6 15]] should give 15 as
output.
Exercise 8.10
Write a function with a matrix as input and a Boolean value as output. The output is true if the input
matrix is a magical square. A matrix is a magical square if it is 1) a square matrix and 2) the sum of all
rows, columns and diagonals are equal to each other.
Use your function to check whether magic(8) is really a magic matrix. Also check whether a square
matrix of 4 4x4 magical squares (making an 8x8 matrix) is a magical square.

59

## Example 8.3 a practical application

The measurement data of an experiment are stored in the file experimental_result.mat. During
the experiment however an overexcited master student who was having too much fun with Matlab
on the lab computer accidentally knocked over the sensor. When looking at the data it is not possible
to see whether any useful data was obtained.
plot(time,output,'.')

Due to the bad values from the sensor, the good values cannot be interpreted. We know that the
actual values of the experiment should be below 1 so luckily this is easily corrected.
good_values = output<1.01;
figure
plot(time(good_values),output(good_values),'.')

Now it is visible that the bad data was in a part of the experiment that was not that important.
This is a silly simple example, but when handling large datasets it is extremely handy to select for the
data of your interest this way.

60

The following exercises are challenging and are meant for those who like to try.
Challenging exercise 8.1
Write a function that has two vectors as input. The function needs to remove all values of the second
vector from the first vector.
When input 1 is [1:10 1:10]
and input 2 is [2 5 7]
Then the output should be:
1

10

10

Note that the Matlab built in function setdiff works like unique and removes all double values
from the output and can therefore not be used for this exercise.
Challenging exercise 8.2
Create a function that has a matrix as an input and gives as output two vectors. The first vector
contains a single copy of all the values that occur in the input matrix. The second vector contains how
many times those values occur.
The input
1
2
3
4

2
3
4
5

3
4
5
6

4
5
6
7

Gives as output
1

and

61

9. Debugging
The first thing to do when you get an error message is to read it THOROUGHLY and try to understand
what is wrong. Usually Matlab describes the nature of the error very well and will also give the
location where the error occurred. It is often possible to click on the number of the line of the code
when encountering an error while running an m-file. Additionally to the right of the scroll bar of the
editor there is some grey space with a square on top. If the square is green there are no warnings or
syntax errors. When it turns orange, Matlab warns you about your code. When this happens in the
grey space beneath the square some orange lines appear. When hovering over such a line, the line of
code producing the warning and the warning are shown. When the square is red your code has a
syntax error and cannot be executed. You have to fix all the red lines before the code can be
executed.
9.1 List of common errors
Inner matrix dimensions must agree
Example: [1 2 3; 4 5 6] * [1 2 3; 4 5 6]
This error is produced when an improper matrix matrix multiplication is performed. If it was the
intention to do an element-wise multiplication * needs to be replaced with .*. Otherwise at least
one of the matrices has not the proper size or dimension.
Index exceeds matrix dimensions
Example:
A = ones(2,3)
A(3,2)

This error is produced when you try to access an element from outside the boundaries of a matrix. It
is possible that the row and column index got switched. It is also possible that the variable containing
the matrix was overwritten and is no longer a matrix.
Undefined function or variable
Examples:
clear
A(3,2)
clear
A

This error is produced when you try to access a variable or an element in a matrix that does not exist.
It is also possible that you tried to call a function that is not in your current working folder. In the
case of the variable and matrix make sure you did not accidently delete a variable in your code
somewhere. In the case of the function make sure you are in the correct working folder and make
sure that the function is present in that folder. Another common mistake producing this error is
making a type-o. For example:
62

interpolotation_facotr = 1.4
next_step = interpolotation_factor.*3

## Too many input arguments

Example:
A = @(x) 1 + x x^2
A(3,2)

This error is produced when you try to give too much input arguments to a function. It is also
possible that you saved one of your own functions with the same as a built in Matlab function, such
as fsolve.m. This overrules the built in function and that is why you must NEVER name your own
functions the same as Matlab functions.
The expression to the left of the equals sign is not a valid target for an assignment
Example:
a = 3;
if a = 3
disp('a = 3')
end

This error is produced when you forget the double equal sign in a condition. This is a very common
mistake.
At least one END is missing:
Example:
a = 3;
if a == 3
disp('a = 3')

This error is produced when you forget an end for a loop or a conditional statement somewhere. Use
smart indentation to see the structure of your code. First select everything (ctrl + a) and then use
smart indentation (ctrl + i).
Unbalanced or unexpected parenthesis or bracket
Example:
A = ([1:4 8:12)]

This error is produced when you make a mistake with parenthesis or brackets. Matlab will point with
the | sign in the error message where the error occurred. Also when you are in the editor and you
click on a parenthesis or a bracket, Matlab will underscore the matching opening or closing
parenthesis or bracket.
One last tip, look at the coloring of the code. By default keywords (function, for, if, end (when not
used for indexing)) are blue, strings are purple, comments are green. When you do not see coloring
at all your code may not be properly save as .m file. When you see wrong coloring you should look at
the code what it is wrong.
63

9.2 Debugging
Matlab also possesses a debug mode, which is a very nice feature to track what is going on in your
code. This is very handy for testing and tracing errors. It is very well possible that your code runs
without any errors, but does not produce the proper result. In such cases the debug mode useful to
find out where exactly the code goes wrong.
In the menu tabs there is a tab Editor. On this tab there is a button Breakpoints with all debug
options. To start the debug mode, go to the line where you want to set a so called break point and
press F12. It is also possible to click the black line next to the line number to the left of your editor
window. A break point is indicated by a red dot on the left side of the code. When Matlab encounters
a breakpoint while running code it will pause there and you are able to see the values of variables.
Next you can step by step through your code by hitting F10 for every step or you can run the rest of
the code to the end or until the next breakpoint by hitting F5. By hitting shift + F5 you can stop
executing the code while in debug mode.
Note that executing clear all also clears your breakpoints in your saved files whereas executing
clear does not.

64

The code of the following exercises can be downloaded from blackboard. The scripts contain
mistakes however and need to be debugged.
Exercise 9.1
Download the code from blackboard and debug it. The function takes a vector as input and calculates
the absolute difference between values next to each other in the input vector. The differences are
given as a vector in the output.
The input reshape(magic(3),1,9) should give the following output
5

Exercise 9.2
Download the code from blackboard and debug it. The function takes a matrix as input and puts the
values of those matrix on the diagonal of the output matrix. The values are taken from the first row,
then the second row, etc.
The input [1 2 3; 4 5 6; 7 8 9] should give the following output
1
0
0
0
0
0
0
0
0

0
2
0
0
0
0
0
0
0

0
0
3
0
0
0
0
0
0

0
0
0
4
0
0
0
0
0

0
0
0
0
5
0
0
0
0

0
0
0
0
0
6
0
0
0

0
0
0
0
0
0
7
0
0

0
0
0
0
0
0
0
8
0

0
0
0
0
0
0
0
0
9

65

The following exercises are challenging and are meant for those who like to try.
Challenging exercise 9.1
Download the code from blackboard and debug it. A colleague gave you a piece of code and went on
vacation. The code however is not working and even worse; he didnt comment a single line of code!
The code is supposed to grow biomass every time step in cells represented by vector elements.
Whenever a critical biomass concentration is reached, the cells divide. The biomass is then divided
over the two daughter cells as shown in figure 9.1.
2.3

10.4

6.7

division
2.3

5.3

5.1

6.7
Figure 9.1. A division of a cell represented by a vector element into two vector elements.

66

10.

Full algorithms

## 10.1 Code implementation

To maintain a good overview in your code, it may be a good idea to make several chapters in your
code with different functions. An algorithm usually has several distinct parts. From top to bottom
they are:
Parameters & variables
The first part in almost all codes is the part where all the parameters and variables are defined. Even
when variables are needed much later in the code, I usually group them here to 1) have an overview
of all my variables, 2) make sure I do not give 2 variables the same name and 3) all similar parameters
are grouped together making it easy to find a specific variable.
The Engine
This is the working part of the code and describes what happens with the defined input and
variables. This part of the algorithm takes up most of a flow chart. In a fair amount of codes the
engine is contained in one or more loops.
Output
In this part of the code all the results are exported, displayed, saved and passed on to calling
functions.
You can write these parts in any order. Some people like to start at the top and work towards the
output. Personally I like to start at the output and work my way towards the initialization. If I need a
new variable I define it at beginning of the code. This way no unnecessary information is brought into
the code.

67

Example 10.1
Write a player versus player version of the game Tic-Tac-Toe in Matlab.
Step 1: Identify the problem
A piece code needs to be written to be able to let two people play Tic-Tac-Toe. The code needs to be
able to process the players input, it must keep track of the previous inputs and every turn it needs to
check whether conditions for a win or a draw are met. Also the script must alternate between
players at the end of the turn.
Step 2: Draw the logic flow

Initialize game

player for input
The input is
correct

False

True

Update board

The active
player won

False

True

Show winning
player

This situation is
a draw

False

Change active
player

True

Show draw

## Figure 9.1. Logic flow for example 9.1

Step 3: Write the code
Initial considerations. This code can be written to display fancy graphics, but a simple matrix
representation in the command window is also possible. This will keep things simple and to the point.
There is no strong input output relation that can be passed on the variables so this code will be a
script and not a function.

68

clc
clear
%%% Parameters & variables %%%
winning_player = 0;
%%% Engine %%%
%%% Output %%%
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end

Next the playing field needs to be defined. For this I use a 3 by 3 matrix. A second matrix,
locations, is made so that the player can see what position corresponds with which number. For
player convenience the numbers are placed so that they match with numeric pad (numpad) on the
keyboard.
clc
clear
%%% Parameters & variables %%%
winning_player = 0;
board = zeros(3);
locations = rot90(reshape(1:9,3,3));
%%% Engine %%%
display(locations)
display(board)
%%% Output %%%
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end

69

Next the input of the player will be written. For this a distinction between the two players needs to
be made. For this the variable acting_player is introduced which has either the value 1 or 2. I
made it so that the starting player is randomly chosen. Also the game keeps going until the game is
finished. Because it is not known how many iterations are needed, a while loop is used. The progress
of the game is checked with the variable isfinished. At the end of the turn the inactive player
becomes the active player.
Please be careful when copying the code below into Matlab. The code wraps to the next line while in
Matlab they do not. If a line does not fit on a single line here it needs to be put back at the end of the
previous line in Matlab.
clc
clear
%%% Parameters & variables %%%
winning_player = 0;
board = zeros(3);
locations = rot90(reshape(1:9,3,3));
acting_player = randi([1 2]);
isfinished = 0;
%%% Engine %%%
while ~isfinished % loop while game is not finished
display(locations)
display(board)
players_choice = input(['Player ' num2str(acting_player) ' input your
choice ']);
board(players_choice==locations) = acting_player; % fill in the value
on the board
acting_player = setdiff([1 2],acting_player); % change the active
player
end
%%% Output %%%
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end

70

Next a check is made whether the input of the player is valid. An input is valid if it is a whole number
between and including 1 and 9 and is not filled in on the board yet. Another variable, open_places,
is made to keep track which places on the board are still open.
clc
clear
%%% Parameters & variables %%%
winning_player = 0;
board = zeros(3);
locations = rot90(reshape(1:9,3,3));
acting_player = randi([1 2]);
isfinished = 0;
open_places = 1:9;
%%% Engine %%%
while ~isfinished % loop while game is not finished
isfine = 0;
while isfine == 0 % loop to make sure the player input is okay
display(locations)
display(board
players_choice = input(['Player ' num2str(acting_player) ' input
if isnumeric(players_choice) && numel(players_choice) == 1 &&
~isempty(intersect(players_choice,open_places)) % continue if input is okay
isfine = 1;
end
end
open_places = setdiff(open_places,players_choice); % remove the choice
from the list of available choices
board(players_choice==locations) = acting_player; % fill in the value
on the board
acting_player = setdiff([1 2],acting_player); % change the active
player
end
%%% Output %%%
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end
display(board)

Lastly a check is implemented to see whether the acting player won the game or whether there is a
case of draw. The game is won when a player made a horizontal, vertical or diagonal line of three and
the game is a draw if all places are filled and there is no winner. If one of these is the case, the loop is
exited and the result of the game is displayed.

71

clc
clear
%%% Parameters & variables %%%
winning_player = 0;
board = zeros(3);
locations = rot90(reshape(1:9,3,3));
acting_player = randi([1 2]);
isfinished = 0;
open_places = 1:9;
%%% Engine %%%
while ~isfinished % loop while game is not finished
isfine = 0;
while ~isfine % loop to make sure the player input is okay
display(locations)
display(board)
players_choice = input(['Player ' num2str(acting_player) ' input
if isnumeric(players_choice) && numel(players_choice) == 1 &&
~isempty(intersect(players_choice,open_places)) % continue if input is okay
isfine = 1;
end
end
open_places = setdiff(open_places,players_choice); % remove the choice
from the list of available choices
board(players_choice==locations) = acting_player; % fill in the value
on the board
% check for win
check_for_win = board == acting_player;
if any(all(check_for_win)) || any(all(check_for_win,2)) ||
all(diag(check_for_win)) || all(diag(rot90(check_for_win)))
winning_player = acting_player;
isfinished = 1;
end
% check for draw
if isempty(open_places)
isfinished = 1;
end
acting_player = setdiff([1 2],acting_player); % change the active
player
end
%%% Output %%%
clc
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end
display(board)

72

The code works now, but there are some optimizations to be made. A clc is added in the loop to
make the output during the game better. Also the draw condition can be processed in the loop
condition to condense the code. Then by putting a break in the win condition the variable
isfinished becomes obsolete and can be removed. Also the variables and parameters can be
grouped to give you a better overview. The final code is available for download on blackboard.
clc
clear
%%% Parameters & variables %%%
winning_player = 0;
acting_player = randi([1 2]);
board = zeros(3);
locations = rot90(reshape(1:9,3,3));
open_places = 1:9;
%%% Engine %%%
while ~isempty(open_places)% loop while game is not finished
isfine = 0;
while ~isfine % loop to make sure the player input is okay
clc
display(locations)
display(board)
players_choice = input(['Player ' num2str(acting_player) ' input
if isnumeric(players_choice) && numel(players_choice) == 1 &&
~isempty(intersect(players_choice,open_places)) % continue if input is okay
isfine = 1;
end
end
open_places = setdiff(open_places,players_choice); % remove the choice
from the list of available choices
board(players_choice==locations) = acting_player; % fill in the value
on the board
% check for win
check_for_win = board == acting_player; % generate a Boolean matrix
if any(all(check_for_win)) || any(all(check_for_win,2)) ||
all(diag(check_for_win)) || all(diag(rot90(check_for_win)))
winning_player = acting_player;
break
end
acting_player = setdiff([1 2],acting_player); % change the active
player
end
%%% Output %%%
clc
if winning_player == 0
disp('This game is a draw')
else
disp(['Player ' num2str(winning_player) ' won this game'])
end
display(board)

73

Exercise 10.1
Write a script for the game Higher Lower. In this game the computer picks a whole number between
and including 0 and 100. It will then ask the player to guess the number. The script will then display
whether the guessed number is too high or too low. This will continue until the number is guessed.
Exercise 10.2
A protein diffuses randomly in 1D space. At the beginning the protein is in the origin (x = 0). Every
time step the protein diffuses randomly 1 unit to the left (-1) or 1 unit to the right (+1).
a) Write a script that simulates this process for 10 time steps.
b) Adapt the script to calculates the average distance to the origin for 1000 repetitions of 10
time steps.
c) Plot the average distance of the protein to the origin for 1000 repetitions of 10, 100, 1000
and 10000 time steps.
d) According to random walk theory the average distance to the origin, d, is described by the
equation below and depends on the amount of steps, n, performed. Plot this equation in the
same figure as c). Do the results match?

d= n

Exercise 10.3
Design a function that sorts an input vector without using built in Matlab functions such as sort. The
output is the sorted vector.
The input reshape([magic(3); 2 2 10],1,12) should give the following output.
1

10

74

The following exercises are challenging and are meant for those who like to try.
Challenging exercise 10.1
Write a function that does prime factorization. If the input of the function is a numerical value larger
than 1 and is a whole number the function gives all prime numbers the input can be decomposed in
in an output vector. The factorial prime numbers are the prime numbers that when multiplied with
one another, the input is obtained again.
Inputs

Outputs

21
72
5
789456123

3
2
5
3

7
2

6343

13829

## Challenging exercise 10.2

Write a function that calculates the greatest common divisor. The function has two integers (whole
numbers) as input and gives the greatest common divisor of the two inputs as an output. You are not
allowed to use the built-in gcd Matlab function in your code, but you can use it to check the
functionality of your code. The greatest common divisor is the largest possible integer that divides
the two inputs without leaving a remainder. For example 30 and 42 are both divisible by 2, 3 and 6,
therefore the greatest common divisor is for 30 and 42 is 6.
One way of determining the greatest common divisor is the following algorithm (there are others!)
1. If one of the inputs is zero, the outcome is the absolute value of the other input
2. If both inputs are non-zero the inputs are changed into their absolute values
3. If the larger number is divisible by the smaller number, the smaller number is the greatest
common divisor.
4. If the largest number is not divisible by the smaller number, replace the largest number by
the remainder after the division and repeat steps 3 and 4.
Dont forget to test your output.
Table 9.1. A set of inputs and outputs to test your function
Input 1 Input 2 Greatest common divisor
0
0
0
0
5
5
-3
0
3
1
7
1
2
-96
2
-1680
-330
30
204223 205193
1
11550 154770
2310

75

## Challenging exercise 10.3

This problem is called the Monty Hall problem.
Youre in a game show and you have to pick one of three closed doors. Behind one closed door is a
car and behind the other doors are donkeys. After you pick a door the game master opens a door
other than your pick and shows a donkey behind it. Then he asks: Do you want to change your
choice to the last remaining door?
a) Write a script in which you can play this game
b) Adjust the script so that the code already knows what decision to make. Build in the strategies 1)
never change your choice and 2) always change your choice. Run the scenario a 1000 times for both
strategies. Which strategy works best assuming you want the car?

76

11. Appendix
Function 1 cond_st_plotter.m
function cond_st_plotter(func)
close all % close previous figures
xx = 0:0.02:10; % generate a mesh grid for plotting
yy = 0:0.02:10;
[XX YY] = meshgrid(xx,yy);
ZZ = []; % initialize empty answer matrix
for i = 1:length(xx)
for j = 1:length(yy)
ZZ(j,i) = feval(func,XX(j,i),YY(j,i)); % calculate the output of
the function on each meshpoint
end
end
imagesc(xx,yy,ZZ,'alphadata',ismember(ZZ,1:5)) % plot all correct data,
make incorrect data invisible
set(gca,'YDir','normal') % flip Y axis
axis image % sets x axis and y axis to contain the whole image
xlabel('X'); ylabel('Y') % label x axis and y axis
caxis([1 5]) % set color scale
colorbar %show the colorbar
end

77

Script 1 Template.m
%%% initialization
close all
clear
xx = 0:0.02:10; % generate a mesh grid for plotting
yy = 0:0.02:10;
[XX YY] = meshgrid(xx,yy);
%%% add code here to generate the proper matrix ZZ %%%
ZZ = ones(size(XX));
%%%
%%% visualization commands %%%
imagesc(xx,yy,ZZ,'alphadata',ismember(ZZ,1:5)) % plot all correct data,
make incorrect data invisible
set(gca,'YDir','normal') % flip Y axis
axis image % sets x axis and y axis to contain the whole image
xlabel('X'); ylabel('Y') % label x axis and y axis
caxis([1 5]) % set color scale
colorbar %show the colorbar

78