Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers.

Similar presentations


Presentation on theme: "1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers."— Presentation transcript:

1 1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers

2 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 Sum elements in a loop Compute average of values Get min/max values from a loop

3 3 WHILE Loop - Review Generally you have a loop control variable This variable has 3 phases Initialization of variable Change of variable Condition to continue running the 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 4 Loops Review Infinite Loop  The loop condition never becomes false and the loop runs, and runs… Use CTRL-C in the command window to break it (or alt-F4 if infinite loop with dialog boxes)

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

6 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 7 Validate input, cont. Ask first, then loop: numValues = input('Value from 1-10: '); % ask first while (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 10) numValues = input('Value from 1-10: '); end

8 8 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 k = 1:100 disp(k); end The symbol : is a new operator, it's the range operator. 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 9 Range Operator [:] for loops use the range operator 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 10 Range Operator, cont. Examples: (in all examples, there is an implied loop body and end ) % loop 10 times for x = 1:10 % It is not necessary that the values be integers for y = 1.2 : 2.3 : 100.5 % Can use negative steps for z = 10:-2:1 So… when does it stop? Steps of -2 will never “hit” the value of 1…

11 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 12 FOR loops, cont. Which brings up a very important issue: It is possible to change the loop counter while in the body of a FOR loop This is normally not a good idea since the value will revert back in the next loop iteration

13 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 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 Test the Code! Write a program that prints all days of the year for the decade, Year, Month, Days

15 15 Loops: Running Totals / Running 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 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 17 Loops: Compute Average 1.Initialize sum before the loop sum = 0; 2.Keep a running total in the loop: sum = sum + number; 3.After loop, divide by count average = sum / iterations;

18 18 FOR Loop: Average Generate 10 random values between 0 and 1 then 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);

19 19 Output results 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

20 20 FOR Loop: Roll Dice 10 times Combine the for loop, with ceil, and rand %loop 10 times for x = 1:10 %generate a die roll dice = ceil(rand*6); %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

21 21 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 number is greater than maximum if so, change maximum to contain this new biggest value if (number > max) max = number; end There are also functions min() and max() – we will use them later with vectors & arrays

22 22 Loops: Find Min / Max N = input('How many values? '); for count=1:N number = input('Please give me a number: '); if count==1 min_val = number; max_val = number; end % of if if number > max_val max_val = number; end if number < min_val min_val = number; end end % of for

23 23 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!

24 24 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

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

26 26 Solution % set up counters odd_cnt = 0; even_cnt = 0; %loop to create/analyze numbers for cnt=1:200 value = floor(rand()*100) + 1; if mod(value, 2) == 1 % odd number odd_cnt = odd_cnt + 1; else % even number even_cnt = even_cnt + 1; 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

27 27 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…

28 28 Final Project Introduction

29 29 Final Project The descriptions provided here are only acting as summaries – please see the complete description on your section's website. Goal Create a project of your choosing within the constraints specified by your instructor. The goal of your project is to logically implement as many of the semester topics as possible, consistent with your project's purpose.

30 30 Final Project, cont. While all topics contribute to the grading of the project, heavy emphasis is assigned to the proper use of: Algorithm Complexity and efficiency Programmer-defined functions Loops File I/O

31 31 Final Project, cont. Connect 4 Hunting Database MP3 player Keyboard DDR Drum Hero Will a beam break? Fuel efficiency and gas cost Ball and wall collision Automatic toll system Forces in a car crash Electrical circuit analysis Examples of past projects: Audio Analysis Serial Port IM Thermistor Data Collection Bezier Curve Fit Unit Conversion Tournament Generation Deal or No Deal Load and moment distribution on a beam w/ plotting Captain's Jack Sparrow's magical compass

32 32 Final Project, cont. Possible areas for new projects: Genealogy Thermodynamics Computational Fluid Dynamics Image / Visual Processing Model Rocket / RC Plane Telemetry 2D / 3D environment modeling Orbital Mechanics

33 33 Final Project, cont. Extra Credit is provided for: Innovative project concepts Advanced programming techniques Exceptional program development

34 34 Final Project, cont. Today is Tuesday October 2, 2012 Projects will be due around December 5. This gives you about 8 weeks. - One week to pick a topic - Two weeks to plan and modify your design - Five weeks to code, revise, and test Past students have quoted about 30 hours dedicated to the project. If we assume virtually all of that was coding, you can plan on spending 6 hours per week on the coding portion – IF you give yourself enough time.

35 35 Final Project, cont. Begin planning! - Find an idea: what interests you? - Discuss with your instructor - Layout a plan for what it will entail - You should be coding by Oct. 22! - If you start early, there is time to revise


Download ppt "1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers."

Similar presentations


Ads by Google