3. Loops and cycles
In the last section we learnt how to plug functions into Matlab and how to plot them.
In this section, we learn to use loops as well as plotting results using different variables. Loops are great for repeating the same set of equations or operations. They are great for stuff like simulating a population over time, or creating a matrix from raw data.
Loops
What is a loop in programming? Think as if you’re trying to write a program for a robot whose job is to apply a vaccine to each of 50 children from a school (I know, those poor kids.. I’m not a ‘real’ doctor). You would specify the exact procedure which is to be applied for each child — prepping the area with alcohol, draw x ml of vaccine into needle, find vein, poke… inject…etc etc. Now instead of writing/repeating the procedure in code over 50 times (once for each child), using a loop you only need to write it once — a loop repeats the same procedure however many times you want. This kind of loop is called a for loop. It is called a “for” loop because it begins with a “for”..
A quick, simple example of a for loop:
Remember Matlab and other programming languages read code from top to bottom, line by line. Upon reaching Line 6 when it reads “for x = 1:10”. If you recall, “x = 1:10” means x = [1 2 3 4 5 …10].
How Matlab reads the loop:
When Matlab first gets to Line 6, it reads x = 1
so Line 8 would be a(1) = 1
and then Line 10, end of loop.
After which it loops back to Line 6 it reads x = 2
Line 8 would be a(2) = 2,
Line 10 end of loop. Back to Line 6, x = 3.
So on and so forth, until x = n(and n =10).
So what you’ve done is fill out the vector ‘a’ one number at a time (more precisely one column at a time).
In conjunction with array indexing (i.e. plugging in values through coordinating the locations on arrays — by filling out rows and columns, like how you filled out the vector ‘a’), a lot of interesting things can be done.
Chaos
Next let’s try something fun: Chaos Theory, also known as May’s
Logistic Map. A relatively simple equation — but lots of mystique:
The subscripts for x just indicates the current x (i.e. the n — th x) and the x after it (the n+1 — th x).
So, the above equation into words: “the next x is equal to/defined as: r times the current x times (one minus the current x)”. Of course, the next x has another x after it, so on and so forth — all defined by this equation.
Let’s not worry about r for now. Plug the equation into Matlab.
So far so good, we will get the next x for any value of x (after we defined r). But how about the x after that? We will need to copy and paste the equation below it again. And the one after? Should we continue pasting it below? As you can see, just like how we would program our vaccination robot, we’ll want to use a loop instead.
If we want to have 65 values for x — i.e. to record/run x over 64 loops (we could have the first number in the vector as the starting x). x is to be a vector 65 numbers long, so that we can record and plot all values that x takes.
With x = r*x*(1-x) — you only get one value of x as the output. After looping it 64 times, you’ll just get the 65th x as the answer. Therefore we need to make x into a vector to save data, as we did with a in the previous example.
Lets write this as a function. The inputs will consist of starting x and r. This will allow you to try out different values of r.
function x = function_name(initial_x, r)
In this particular model, r should take a value between 0 and 4, and initial/starting x should be between 0 and 1 (see wiki page).
Let’s plot the thing as well because why not! A picture can be worth a thousand words. Remember when plotting, the x-axis must also be a vector, same as the y-axis (vector x is to go on the y-axis — it is the “dependent” variable). On the y-axis, it’s just a matter of how many x values you looped through — how many numbers are in vector x (i.e. 1:65, alternatively use 1: size(x, 2)).
If you feel you’ve got this, go ahead give it a try! If not that’s okay. It does takes a little time to get used to.
The solution is given below:
In Chaos Theory, similar but different values of r give very different results to x. So we would want to try out different values of r.
There are a number of ways to do this, we’ll go through the simplest and most efficient way. For instance, we want to try out three different r’s (1.5, 2.5, and 4) and plot them onto the same figure. First we must add a line to hold on to each of the three line plots that we make .
Enter the function “hold on” between Line 15 and 16. Save the file.
Type this in the Command Window:
chaos(0.1, 1.5); chaos(0.1, 2.5); chaos(0.1, 4);
Sometimes, you’ll want to use a loop within another loop (imagine filling out a 5 row by 10 column excel table (i.e. 5 x 10 matrix) — within each one of the 5 rows, you’ll need to fill out each of 10 columns. In this case, there will be a loop for filling columns within a loop for filling rows.
Note: Running loops is very time consuming on MATLAB compared to R and other programs. It might be okay running short programs like this, but running loops with MATLAB can be 1000 times slower for programs with lots of data! The reason for this is MATLAB is geared towards array operations/manipulations using other arrays, termed “Vectorisation” (←see link — also introduced in the next section), and other methods that bypass the use of loops.
In the next section we’ll be looking at relational and logical operators to compare array variables, and to operate on arrays.
R
- Loops
a = c()
for (x in 1:10) {
a[x] = x
}
Note:
An ‘end’ after ‘for’ is not required — use { } instead.
The vector ‘a’ must first be initialised as something before the loop. In this case, a = c( ) creates a blank vector — equiv. a = [] - Chaos Theory
^Check the “Source on Save” box to avoid clicking on “Source” every time you want to call the function. Click on the Save button to save your changes.
Unlike Matlab, Environment/Workspace should be cleared before running a function if just running it by itself.
x = numeric(t) is an alternative to x = c( ). R doesn’t like creating objects inside a loop whereas Matlab is okay with it.
Line 9: Starting this line with “x[i] =” or “x[i+1] = ” both works. Just have to change the other indexing accordingly (compare the Matlab and R examples).
{ }’s are vital in R.
Line 13: Setting (type = “o”) connects the dots with lines
Line 12: length(x) is number of elements in x in R. In Matlab, length(x) is number of columns ( size(x,2) or length(x) )
Just like in Matlab, this function can be called by using chaos(a,b) e.g. chaos(0.1,2.5) or chaos(0.1,4)