Loops - PowerPoint PPT Presentation

loops n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Loops PowerPoint Presentation
play fullscreen
1 / 42
Loops
204 Views
Download Presentation
santos
Download Presentation

Loops

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Loops WHILE loops FOR loops Range operator Running totals Random Numbers Floor/Ceiling Modulus Library functions - vocabulary

  2. Review • Review while loops while(time < 3:15) • Review infinite loop while (true) • Introduce for loop for x = 1:10 • Introduce range operator x=1:10 or x=1:2:10 • Introduce random value generator rand • Introduce ceiling and floor functions • Sum elements in a loop • Compute average of values • Get min/max values from a loop

  3. 1. WHILE Loop - Review • Generally you have a loop control variable, this variable has 3 phases • Initialization of variable • Change of variable • Condition to exit loop • Example: the loop control variable is x x = 0;  1. initialization while ( x < 10)  2. condition x = x + 1;  3. change loop variable fprintf(‘%02d\n’, x); end

  4. Loops Review • Infinite Loop  Loop control variable never meets the condition and the code runs and runs……. • Use CTRL C in the command window to break it

  5. Loop Review Why is this an infinite loop in MATLAB? x = 11; % 1. initialization while ( x > 10) % 2. condition fprintf(‘%02d\n’, x); x = x + 1; % 3. change loop variable end

  6. Trap a user for a value • Ask a user for a value between 1 to 10 • What if they don’t give the proper value? Two approaches: • Ask first, then loop • Make bad and loop

  7. Validate input, cont. Ask first, then loop: numValues = input(‘Value from 1-10: ’); %ask first while (numValues<1 || numValues>10) numValues = input(‘Error! Enter a value 1-10: ’); end Make bad, then loop: numValues = -1; %makes loop run at least once while (numValues<1 || numValues>10) numValues = input(‘Value from 1-10: ’); end

  8. 2. FOR Loop • Generally used for a fixed number of iterations • You know you want to go from 1 to 100, by ones • for syntax does all 3 parts of the loop in one line initialization, change, condition for i = 1:100 disp(i); end The symbol : is a new operator, it’s the rangeoperator. The range is from 1 to 100, by ones. We say “in steps of one” If you want to loop in steps of 2, use 1:2:100

  9. Range Operator [:] • for loops use the rangeoperator to specify a range of values to loop over (to iterate) • Syntax: variable = start : increment : end : increment is optional – defaults to : 1 if omitted

  10. Range Operator, cont. Examples: (in all examples, there is an implied loop body (code-block), and end) % loop 10 times for x = 1:10 % None of the values MUST be integers for y = 1.2 : 2.3 : 100.5 % Can use negative steps for z = 10:-2:1 Steps of -2 will never “hit” the value of 1… So… when does it stop?

  11. Range Operator, cont. The loop continues as long as the value is “in the range” specified for ctr=1:3:10 % as long as 1<=ctr<=10 for val=-5:2:5 % as long as -5<=val<=5 for thing=5:-3:0 % as long as 5>=thing>=0

  12. FOR loops, cont. Which brings up a very important issue: It is possible to change the loop counter in a FOR loop This is normally not a good ideasince the value will be changed in the next loop iteration

  13. FOR loops, cont. for cnt=1:5 fprintf(‘%d\n’, cnt); cnt = cnt * 2; end Output: 1 2 3 4 5 >> Notice that the variable changed back at the top of the loop

  14. Nested for loops Generate a table of output that looks like a clock for every second of the day for hr= 0:23 % all hours for day for min = 0:59 % all minutes per hour for sec = 0:5:59 % all seconds per min per hour fprintf(‘%02d:%02d:%02d\n’, hr, min, sec); end end %01:05:05d end Test the Code! Write a program that prints all days of the year for the decade, Year, Month, Days

  15. Loops: Running total / products • Loops are useful for accumulating or summing values..computing averages, totals etc. (“running totals”, “running products”) • Running total: • Start with a variable for the sum initialized to 0 sum = 0; • Each time through loop add a value to the sum: sum = sum + number; • Running product: • Start with a variable for the product, initialized to 1 prod = 1; • Each time through loop, multiply: prod = prod * number;

  16. Loops: Running total % initialize values total = 0; value = 0; %loop when value positive or zero while value >=0 fprintf('Negative values quit…\n') value = input('Enter a positive integer: '); if value >=0 %add value if positive total = total + value ; end % of if end % of while %display result fprintf('total = %d\n', total);

  17. Loops: Compute Average • Initialize sum before the loop sum = 0; • Keep a running total: sum = sum + number; • After loop, divide by count average = sum / iterations;

  18. 3. Random Numbers • rand - generates a pseudo random number between 0 and 1 (exclusive) • never 0 and never 1: some value between. • Go to MATLAB • >> rand • >> help rand • Big picture: Why use random numbers? • Create tables of data so you can test code • Let computer decide who starts a game (player 1,2,3…?) • Introduce random events when testing software (1 signifies main engine is down, 2 signifies fuel sensor error...)

  19. FOR Loop: Average • Generate 10 random values (between 0 and 1) and compute average %initialize variables sum = 0; average = 0; %loop 10 times for x = 1:10 value = rand; %generate 1 random value ]0-1[ fprintf(‘value %02d is %.3f\n’, x, value); sum = sum + value; end %calculate, display average average = sum / 10; fprintf (‘the average is %.3f\n’, average);

  20. Output result Second run: value 01 is 0.971 value 02 is 0.957 value 03 is 0.485 value 04 is 0.800 value 05 is 0.142 value 06 is 0.422 value 07 is 0.916 value 08 is 0.792 value 09 is 0.959 value 10 is 0.656 The average is 0.710 First run: value 01 is 0.906 value 02 is 0.127 value 03 is 0.913 value 04 is 0.632 value 05 is 0.098 value 06 is 0.278 value 07 is 0.547 value 08 is 0.958 value 09 is 0.965 value 10 is 0.158 The average is 0.558

  21. 4. floor/ceil Functions • floor and ceil (ceiling) functions convert fractional numbers into integers. Similar to rounding but instead they take the next integer lower for floor, higher for ceil

  22. Combine rand with ceil • Lets say you are rolling a dice, rather then asking the user: dice = input(‘select roll (1-6): ’) • Let Matlab pick a random number: dice = ceil(rand * 6) • rand gives you .01 .. 0.99 • Six times that gives you .06 .. 5.94 • ceil(.06)  1 • ceil(5.94)  6 Thus you get random values for dice between 1..6

  23. Combine rand with floor • What if you want values from 0 to 5 • value = floor(rand * 6); • rand gives you .01 .. 0.99 • Six times that gives you .06 .. 5.94 • floor(.06)  0 • floor(5.94)  5 Thus you get random values from 0 to 5 inclusive using the command: value = floor(rand*6);

  24. Pick a random value between-10 and 10 • What if you want values from -10 to 10 inclusive? • value = floor(rand * 21) - 10 • rand gives you .01 .. 0.99 • 21 times that gives you .21 .. 20.79 • floor(.21) 0 • floor(20.79)  20 • Subtract 10 gives you -10 to 10 inclusive Thus you get random values from -10 to 10 inclusive using the command: value = floor(rand * 21) - 10

  25. For Loop-Roll Dice 10 times • Combine the for loop, with ceil, and rand %loop 10 times for x = 1:10 dice = ceil(rand*6); %generate a dice roll %display fprintf(‘roll %d is %d\n’, x, dice); end roll 1 is 1 roll 2 is 6 roll 3 is 6 roll 4 is 5 roll 5 is 5 roll 6 is 5 roll 7 is 3 roll 8 is 4 roll 9 is 2 roll 10 is 5

  26. 5. Loops: Find Min / Max • Trying to find a min value or max value • First time through the loop, set the minimum and the maximum value to the number. if (count == 1) min = number; max = number; end • Each subsequent time, determine if the number > maximum if so, reset the maximum value to the number if (number > max) max = number; end There are also functions min() and max() – we will use them later with vectors & arrays

  27. Taboos http://www.egr115.com/taboos.pdf Don’t use these words in your programs: • global • persistent • break • continue • error • exit • quit MAJOR points lost for using these in your programs!

  28. 6. Modulus • help mod • Determines the long division remainder value mod any number with N, the function will return from 0 to N-1 If evenly divisible, mod will return 0 i.e mod (6, 3) or mod (100, 10)

  29. Combine for / rand / mod • Write a program that picks 200 random integers between 1 .. 100 • Determine how many are odd and how many are even • Print out the # of odd values, # even values, and compute the percentages of odd and even values

  30. An algorithm for ??? pick rand number if odd Increment odd counter else Increment even counter end end Compute odd percentage Compute even percentage Print out results Note counters need to be INITIALIZED to 0. Before or in the loop?

  31. Solution % set up counters odd_cnt = 0; even_cnt = 0; %loop to create/analyze numbers forcnt=1:200 value = floor(rand()*100) + 1; if mod(value, 2) == 1 %even number odd_cnt = odd_cnt + 1; else %odd even_cnt = even_cnt + 1; end end %calculate/display results odd_pct = 100* odd_cnt / 200; even_pct = 100 * even_cnt / 200; fprintf(‘%.2f%% were odd,’, odd_pct); fprintf(‘and %.2f%% were even\n’, even_pct); Notice the lack of semicolons (;) in FOR and IF statements

  32. How long to generate random #’s • Write a program that generates random numbers from 1 – 100 • Keep running program ‘til every number gets one occurrence. – that’s an array problem, have to do that in a week or so…

  33. Library functions

  34. Library Functions What is a function? Generally, a function is a set of commands which are grouped to perform in sequence, like a program. The function is provided a name so that a new program can use the function. Functions are a foundation of “modularity” – when we’ve solved a problem, let’s allow it to be reused. If there’s a problem with the solution, we can fix the function without re-writing the programs that use.

  35. Library Functions, cont. We have already used or seen several functions: clc, clear, fprintf, input, rand, floor, ceil “Libraries” are groups of functions usually related in some way. Those functions listed above are considered “library functions” because they are provided as a group with MATLAB – we don’t have to write them ourselves.

  36. Library Functions, cont. A few of the many, many MATLAB functions: • sin(), cos(), tan() • sind(), cosd(), tand() • asin(), acos(), atan() • asind(), acosd(), atand() • exp(), sqrt(), log(), log10()

  37. Library Functions, cont When we use a function we say that we are “calling the function”. The code calling the function is referred to as the “function call”: v = 6 * rand(); The function call

  38. Function Calls Functions frequently require information to achieve the goal for which they were written. This information is sent to the function inside parentheses after the name of the function in the function call: x = sqrt(a); The values sent (there may be more than one) are called arguments to the function. a is an “argument” to the sqrt() function.

  39. Function Calls, cont. A function, when executed, typically sends information back to the program that asked it to execute. We say that the function “returns a value” - it has a return value. If we choose to, we can “collect” the return value: we save it in a variable.

  40. Function Calls, cont. We usually choose to collect the return value: X = sqrt(a); But not always – you don’t usually see this: Y = fprintf(‘Hello!’) X collects the return value Y collects the return value

  41. Function Calls, cont. Not all functions return values. But many do. You, the programmer, MUST provide the arguments when calling a function. You, the programmer, MAY choose to collect the return values.

  42. Function Calls, cont. Terminology summary Function call – the command that executes a function Arguments – inputs to a function call Return values – outputs from a function call