Professional Documents
Culture Documents
4.1 Loops
A loop is a way of repeatedly executing a section of code. It is so important to know how to write them that several common examples of how they are used will be given here. The two kinds of loops we will use are the for loop and the while loop. We will look at for loops rst, then study while loops a bit later in the logic section. The for loop looks like this:
for n=1:N % Put code here end
which tells Matlab to start n at 1, then increment it by 1 over and over until it counts up to N, executing the code between for and end for each new value of n. Here are a few examples of how the for loop can be used. Summing a series with a for loop Lets do the sum 1 2 n =1 n with N chosen to be a large number.
Listing 4.1 (ch4ex1.m)
N
(4.1)
clear; close all; % set s to zero so that 1/n^2 can be repeatedly added to it s=0; N=10000; % set the upper limit of the sum for n=1:N % start of the loop s = s + 1/n^2; % add 1/n^2 to s each iteration end % end of the loop fprintf(' Sum = %g \n',s) % print the answer
Create a breakpoint at the x=0 line in the code, run then code, and then step through the rst several iterations of the for loop using F10. Look at the values of 19