Difference between revisions of "Matlab Loops"

From Sutherland_wiki
Jump to: navigation, search
m (Motivating Example)
m (For Loops)
Line 35: Line 35:
 
| ''' <tt>hi</tt>''' || Indicates the stopping point for the counter
 
| ''' <tt>hi</tt>''' || Indicates the stopping point for the counter
 
|-
 
|-
| '''<tt>inc</tt>''' || Indicates the increment for the counter.  You can increment forward, backward, and in any size increment.
+
| '''<tt>inc</tt>''' || Indicates the increment for the counter.  You can increment forward, backward, and in any size increment.  This is an optional argument, and defaults to 1 if not given.
 
|}
 
|}
 
Each time through the loop, the <tt>counter</tt> variable will increment by <tt>inc</tt>.  The loop exits when the <tt>counter</tt> exceeds <tt>hi</tt>.
 
Each time through the loop, the <tt>counter</tt> variable will increment by <tt>inc</tt>.  The loop exits when the <tt>counter</tt> exceeds <tt>hi</tt>.
Line 141: Line 141:
 
  |}
 
  |}
 
|}
 
|}
 
  
 
== While Loops ==
 
== While Loops ==

Revision as of 17:17, 19 September 2008

Motivating Example

Suppose you wanted to create a program to see how often a given number turns up in Craps. If we roll two dice, the smallest number that can arise is 2, and the largest is 12. While there are more clever ways of doing this using probability, we take a brute-force method. Let's choose two random numbers between 1 and 6 and do this over again until we achieve the number we are betting on.

bet = 4;  % the number we are looking for (between 2 and 12)
dice = round( rand(2,1)*5+1 );  % two numbers between 1 and 6
if ( sum(dice) != bet )
  % now what???
end

The problem is that we want to keep rolling the dice until we get our number (4 in this case). How do we do this? We use loops. There are two kinds of loops: for loops and while loops.

Tips on using loops:

  • If you know how many times you will execute the loop, use a for loop.
  • If you do not know how many times you will execute the loop, use a while loop. This is typically used when you want to do something over and over again until some condition is met.

In our example above, a while loop is most appropriate.

For Loops

A for loop is executed a set number of times. The basic syntax of a for loop is:

 for counter = lo:inc:hi
   % do some work
 end
counter A variable that ranges from lo to hi
lo Indicates the starting point for the counter
hi Indicates the stopping point for the counter
inc Indicates the increment for the counter. You can increment forward, backward, and in any size increment. This is an optional argument, and defaults to 1 if not given.

Each time through the loop, the counter variable will increment by inc. The loop exits when the counter exceeds hi. The following table shows several simple examples of a for loop.

Examples of using for loops
Matlab Code Details Output
for i=5:8
  disp(i);
end
i Action
5 Prints 5
6 Prints 6
7 Prints 7
8 Prints 8
5
6
7
8
x = 1:7;
for i=2:2:length(x)
  x(i) = 2*x(i);
end
disp(x);
i Action
2 x(2) was 2, it is now 4
4 x(4) was 4, it is now 8
6 x(6) was 6, it is now 12
1 4 3 8 5 12 7
x = 3:7;
for i=length(x):-2:1
  fprintf('x(%1.0f) = %1.0f\n',i,x(i));
end
i Action
5 Prints: x(2) = 7
3 Prints: x(4) = 5
1 Prints: x(1) = 3
x(5) = 7
x(3) = 5
x(1) = 3


Let's consider another example: calculate the factorial of a number using a for loop. The factorial is given as

n! = \prod_{i=2}^{n} i\left(i-1\right)

We could implement this using a for loop as shown in the following:

Matlab Code Results at the end of each pass through the for loop
n = 7;    % we want to find n!
nfact=1;  % starting value.
for i=n:-1:2
  nfact = nfact * i;
end
Value of i 6 5 4 3 2
Value of nfact 6 30 120 360 720

While Loops

Unlike a for loop (which is executed a set number of times), the while loop continues to execute until some condition is met. The basic syntax of a while loop is:

 while condition
   % do some work.  Note that "condition" must change inside the loop!
 end

Here is an example of how to calculate the factorial of a number using a while loop.

Matlab Code Results at the end of each pass through the while loop
n = 7;    % we want to find n!
nfact=1;  % starting value.
while n>1
  nfact = nfact*n
  n = n-1
end
Iteration Number 1 2 3 4 5 6
Value of n 6 5 4 3 2 1
Value of nfact 7 42 210 840 2520 5040


Here is another example of rolling two dice. We keep rolling the dice until we get them to add up to 7. We print out how many rolls it took.

clear; clc;
luckyNum = 7;  % our lucky number.
lucky = 0;  % 0 is "false" - we will use this to determine when we hit our lucky number.
nrolls = 0;  % keep track of how many times we roll the dice.
while ~lucky
  % pick 2 random integers between 1 and 6.  The "round" function rounds to the nearest integer.
  dice = round( rand(2,1)*5+1 );
  nrolls = nrolls+1;     % increment the counter for how many rolls we have done.
  lucky = sum(dice)==luckyNum; % decide if we rolled a lucky 7 or not...
end
fprintf('Rolled a lucky %1.0f after %1.0f rolls\n',luckyNum,nrolls);

Here we have used the ~ operator, which is the logical "NOT" operator.