130 likes | 346 Views
MATLAB – Advanced For Loops. Topics Covered: Loops in MATLAB - for–end loops - the break command - the continue command. Examples of for–end Loops. for k = 10 : 2 : 14 disp(k) end. for i = 25: -5 : 10 disp(i) end. Output: 25
E N D
MATLAB – Advanced For Loops Topics Covered: Loops in MATLAB - for–endloops - the break command - the continue command
Examples of for–end Loops for k = 10 : 2 : 14 disp(k) end for i = 25: -5 : 10 disp(i) end Output: 25 20 15 10 Output: 10 12 14
Examples of for–end loops Test these for-end loops: for k = 1 : 3 : 10 x = k^2 end Output: x = 1 x = 16 x = 49 x = 100
Rules for for–end Loops • Every formust have an end • for loops can be used in the command window, in script files, and in function files • A semicolon is not needed after fork = f : s : l (to suppress printing k) • To display the value of k in each pass (sometimes useful for debugging), type k as one of the commands in the loop • Loops can include conditional statements and any other MatLab commands (functions, plots, etc.) • Loops can be put inside of loops
Applications of for–end Loops Find the sum of the even numbers from 2 to 10 Always initialize 'summing' variables sum1 = 0; for n = 2 : 2 : 10 sum1 = sum1 + n ; end sum1 Output: sum1 = 30 Notice that sum1 is set to zero before entering the loop. Why?
for–end loops with vectors Create the vector v = [2 4 6 8]. Calculate and print the square of each element. Output: vs = 4 vs = 16 vs = 36 vs = 64 Program: v = [2 4 6 8] ; for k = 1 : 4 vs = v(k)^2 end
for–end loops with vectors For the vector v = [2 4 6 8], calculate the square of each element and if the square is less than 40, display the square and the message “The square is less than 40” or else display the square and “The square is greater than 40”. v = [2 4 6 8] ; for k = 1:4 vs = v(k)^2; if vs<40 disp(vs) disp(‘The square is less than 40’) else disp(vs) disp(‘The square is greater than 40’) end end Output on next page
for–end loops with vectors 4 The square is less than 40 16 The square is less than 40 36 The square is less than 40 64 The square is greater than 40
180- 184 a = 0; for x=1:10 a = a + 1; if (a == 5) break end disp (a) end … EXAMPLE OF break What will this loop display? 1 2 3 4
180- 184 a = 0; for x=1:10 a = a + 1; if (a == 5) continue end disp (a) end 1 2 3 4 6 7 8 9 10 EXAMPLE OF continue What will this loop display?