5.1for loops 59
The for loop
(http://www.eng.ed.ac.uk/teaching/courses/matlab/unit05/for-loop.shtml)
Self Test Exercise: for loops
Evaluate the following expressions without usingMATLAB. Check your an-
swers withMATLAB.
- How many times will this code printHello World?
1 for a=0:50
2 disp('Hello World')
3 end - How many times will this code printGuten Tag Welt?
1 for a=−1:−1:− 50
2 disp('Guten Tag Welt')
3 end - How many times will this code printBonjour Monde?
1 for a=−1:1:50
2 disp('Bonjour Monde')
3 end - How many times will this code printHola Mundo?
1 for a=10:10:50
2 for b=0:0.1:1
3 disp('Hola Mundo')
4 end
5 end
Listing 5.3 demonstrates an example of using aforloop to take the sum of
a geometric series (the same example posed in Exercise 2, Question 8).
Listing 5.3: for_loop_sum.m - Script to sum a geometric series using aforloop
1 % for_loop_sum.m
2 % Script to sum a geometric series using a for loop
3 %
4 % Craig Warren, 01/09/2011
6 % Variable dictionary
7 % n Number of terms to sum
8 % my_sum Sum of geometric series
9 % r Constant (set to 0.5 for this example)
10 % m Loop counter
12 clear all; % Clear all variables from workspace
13 clc; % Clear command window