Lab 4 – Loops and More Discrete Time Systems

advertisement
Lab 4 – Loops and More Discrete Time Systems
Date: September 13, 2011
Assignment Due Date: September 20, 2011
Goal: In this lab you will learn how to use loops in your code. You will then use loops in writing scripts to
do multiple types of calculation including a script to simulate the discrete time system from last week’s
lab.
New Commands
for() – a loop that repeats lines of code based on the given index vector.
For loops
Today you will learn how to use for loops in programming. This is a very important topic and will prove
very useful and essential in this course as well as any future programming you may encounter. A for
loop allows certain lines of code to be repeatedly executed without having to retype them. We will
begin with a basic example of a for loop and then discuss the parts. Open a new script and add the
following lines of code.
for (i in 1:5){
print(i)
}
Recall from last lab that print(i) should print the value of i to the console. When you execute this code,
what do you notice about the value of i as it gets printed to the console?
The value is changing on each step of the loop! The value “i” is called the index of the loop. It
essentially tells you which step the loop is on. To put this short code into words: “FOR each index value
(1,2,3,4,5), print the index value to the screen”. The above for loop is equivalent to the following code.
print(1)
print(2)
print(3)
print(4)
print(5)
However, for using a for loop we only have to write the print command once! This becomes very useful
if we want to do the same thing many times. Let’s try printing the numbers 1 to 100 to the console.
for (i in 1:100){
print(i)
}
Imagine how tedious it would be to write the print() command 100 times. Loops are very time saving
and effective when coding.
Notice in R that we tell the for loop what index values we want by specifying a vector, in the cases above
we specified 1:5 and 1:100. Let’s change this vector to something completely different.
for (i in c(3,7,0,-4){
print(i)
}
When you execute this code you see that we have changed the values of the index, i, by redefining the
index vector. The lines of code included in the for loop will run for each element in the index vector.
Therefore, your code will run the exact same amount of times as the number of elements you specify in
the index vector. Change the index vector again and make sure you understand this concept. Compare
your results with someone sitting next to you.
When coding, sometimes we will use the index values as part of our calculations inside the for loop.
Other times it will just help us to execute the code a certain number of times. Let’s look at examples of
both.
Using Loops as a Counter
We will start with a case where we use a for loop as a counter. Let’s write a script called plus2.R. We
will use an example to illustrate how this works. Say Jimmy currently has $0 in his savings and just got a
job mowing lawns for $2 per lawn. We want to calculate how much money he has if he mows m lawns.
While we could quickly do this math using algebra, we will write a loop to calculate this sum.
S = 0 #starting amount of money Jimmy has
m = 25 #number of lawns Jimmy has mowed
for (j in 1:m){
S=S+2
}
print(S)
Is the final answer what you expect? Obviously a loop is a much harder way of calculating 2*m but you
should now be starting to understand how to use loops. The loop we wrote above added 2 twenty-five
times. Therefore, for loops are a great way to do the same thing a given number of times. Imagine how
this could have been helpful in last week’s lab.
Let’s now consider how we would write code to compute powers of
make sure we all understand mathematically what this means.
, without using ^. Let’s first
Create a new script called powers.R. We can use a for loop in order to calculate
2^5.
. Let’s first calculate
a=2
m=5
b=1
for (i in 1:m){
b = b*a
}
print(b)
2^5 #check for you to see that our loop actually works.
Why do we need the additional variable b?
When calculating sums or products using loops, we need some sort of starting value to get us going.
Since we are doing a multiplication, it makes sense that we start at b=1 since 1 is the multiplicative
identity. In other words, if we multiply any number by 1 it does not change the number. We actually
initialized the first sum we calculated in plus2.R as well. Since Jimmy had no money we started at 0,
which happens to be the additive identity. We could have changed this value to 10, say, if Jimmy had
$10 in savings.
Take a minute to go through the loop step by step and make sure you know what it is doing. What is b
when i=1, i=2, i=3, i=4, and i=5? Stepping through the elements of the loop one at a time is often the
best way to ensure your loop is doing what you want it to do. This comes in handy when you are getting
unexpected results or errors and need to debug your code.
Change the code to calculate 4^13 and 6^24. Hint: this should be very simple to change!
Using the Index Values Inside the Loop
Now let’s look at an example where we use the actual index values inside the for loop. What if we want
to calculate the sum, 1+2+3+…+m? We can do this using a loop! Again, we will create a new script
called sum.R.
m = 10
a=0
for (i in 1:m){
a=a+i
}
print(a)
Notice that we initialized a to 0 since we are adding these numbers. Check this code for many different
m values and do the calculations by hand to make sure it is correct. Compare your results here with
someone sitting next to you. Also, notice that in this and all the cases above, we are redefining some
variable in each step of the loop. In sum.R, we update a at each step.
Here is another example where can use the actual index values in our calculations inside the loop. Think
back to lab 2 where we had to plot curves for different values of body mass. Loops make this MUCH
easier. We needed curves for M = (10,25,50,75,100). Watch how simple it now is to create these plots
using scripts and a for loop. Create a new script called Lab2.R
k=5
E = function(d){M*d^2/(k^2*M^2+d^2)}
plot(c(0,1100),c(0,90),type="n",ann=FALSE)
title(main = "Antibiotic Efficacy",xlab = "Amoxicillin Dosage (mg)",ylab = "# of Dead Bacteria (*10^8)")
DoseVector = seq(from=0,to=1100,by=25)
for (M in c(10,25,50,75,100)){
lines(DoseVector,E(DoseVector))
}
By specifying our index value as M and the index vector as the different masses we want to plot the
curve for, we can quickly plot each line. You can also use the index values in other ways inside the for
loop. See what happens if you add col = M inside the lines() command.
Using Loops to Simulate Discrete Time Dynamical Systems
Loops will allow you to now efficiently code your simulations of discrete time dynamical systems. Recall
last week how many lines of code you had to write to update your function. You should now be able to
avoid this! Open a new script and save it as Lab3Loops.R. We will now write a loop to simulate the
same system you used in last week’s lab.
Work with those sitting around you to write a loop to simulate this system for t time steps. Make sure
your code prints the amount of medication in the body at each time step. Below I have listed some
helpful hints in writing this code.
 Write your updating function as a function in R (you did this last week). You will use this
function in your loop and only need to type the function once in the loop.
 Be sure to initialize the starting amount of antibiotic appropriately.
 Print the value at each time step using print().
 THIS CODE WILL USE THE LOOP AS A COUNTER, it won’t use the index value in the for loop.
 Compare your results to last week to make sure your loop is doing what you want.
SAVE Lab3Loops.R TO TURN IN AS PART OF YOUR ASSIGNMENT!!!
Download