1 loops & more while loops for loops range operator running totals random numbers

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

If you can't read please download the document

Post on 12-Jan-2016




0 download

Embed Size (px)


  • *Loops & MoreWHILE loops

    FOR loopsRange operatorRunning totals

    Random Numbers

  • *ReviewReview 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

  • *WHILE Loop - ReviewGenerally you have a loop control variable This variable has 3 phasesInitialization of variableChange of variableCondition to continue running the loop

    Example: the loop control variable is xx = 0; 1. initializationwhile ( x < 10) 2. condition x = x + 1; 3. change loop variable fprintf('%02d\n', x);end

  • *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)

  • *Loop ReviewWhy is this an infinite loop in MATLAB?

    x = 9;% 1. initializationwhile ( x > 10)% 2. conditionfprintf('%02d\n', x);x = x + 1;% 3. change loop variableend

  • *Trap a user for a valueAsk a user for a value between 1 to 10What if they don't give the proper value?

    Two approaches:Ask first, then loopMake bad and loop

  • *Validate input, cont.Ask first, then loop:numValues = input('Value from 1-10: '); % ask firstwhile (numValues10) numValues = input('Error! Enter a value 1-10: ');end

    Make bad, then loop:numValues = -1; % makes loop run at least oncewhile (numValues10) numValues = input('Value from 1-10: ');end

  • *FOR LoopGenerally used for a fixed number of iterationsYou know you want to go from 1 to 100, by onesfor syntax does all 3 parts of the loop in one line initialization, change, condition

    for k = 1:100disp(k);end

  • *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

  • *Range Operator, cont.Examples: (in all examples, there is an implied loop body and end)

    % loop 10 timesfor x = 1:10

    % It is not necessary that the values be integersfor y = 1.2 : 2.3 : 100.5

    % Can use negative stepsfor z = 10:-2:1So when does it stop?Steps of -2 will never hit the value of 1

  • *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

  • *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

  • *FOR loops, cont.for cnt=1:5fprintf('%d\n', cnt);cnt = cnt * 2;end


  • *Nested FOR loopsGenerate a table of output that looks like a clock for every second of the day

    for hr= 0:23 % all hours for dayfor min = 0:59 % all minutes per hourfor sec = 0:5:59 % all seconds per min per hourfprintf('%02d:%02d:%02d\n', hr, min, sec);endendendTest the Code!Write a program that prints all days of the year for the decade, Year, Month, Days

  • *Loops: Running Totals / Running ProductsLoops 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 0sum = 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 1prod = 1;Each time through loop, multiply: prod = prod * number;

  • *Loops: Running total% initialize valuestotal = 0;value = 0;

    %loop when value positive or zerowhile value >=0fprintf('Negative values quit\n')value = input('Enter a positive integer: ');if value >=0 %add value if positivetotal = total + value ;end % of ifend % of while

    %display resultfprintf('total = %d\n', total);

  • *Loops: Compute AverageInitialize sum before the loop sum = 0;

    Keep a running total in the loop:sum = sum + number;

    After loop, divide by countaverage = sum / iterations;

  • *FOR Loop: AverageGenerate 10 random values between 0 and 1 then compute average

    %initialize variablessum = 0;average = 0;

    %loop 10 timesfor x = 1:10value = rand; %generate 1 random value ]0-1[fprintf('value %02d is %.3f\n', x, value);sum = sum + value;end

    %calculate, display averageaverage = sum / 10; fprintf ('the average is %.3f\n', average);

  • *Output resultsSecond run:

    value 01 is 0.971value 02 is 0.957value 03 is 0.485value 04 is 0.800value 05 is 0.142value 06 is 0.422value 07 is 0.916value 08 is 0.792value 09 is 0.959value 10 is 0.656The average is 0.710First run:

    value 01 is 0.906value 02 is 0.127value 03 is 0.913value 04 is 0.632value 05 is 0.098value 06 is 0.278value 07 is 0.547value 08 is 0.958value 09 is 0.965value 10 is 0.158The average is 0.558

  • *FOR Loop: Roll Dice 10 timesCombine the for loop, with ceil, and rand

    %loop 10 timesfor x = 1:10

    %generate a die rolldice = ceil(rand*6);

    %displayfprintf('roll %d is %d\n', x, dice);


    roll 1 is 1roll 2 is 6roll 3 is 6roll 4 is 5roll 5 is 5roll 6 is 5roll 7 is 3roll 8 is 4roll 9 is 2roll 10 is 5

  • *Loops: Find Min / MaxTrying 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;endThere are also functions min() and max() we will use them later with vectors & arrays

  • *Loops: Find Min / MaxN = input('How many values? ');

    for count=1:Nnumber = input('Please give me a number: ');

    if count==1min_val = number;max_val = number;

    end % of if

    if number > max_valmax_val = number;end

    if number < min_valmin_val = number;endend % of for

  • *Tabooshttp://www.egr115.com/taboos.pdf

    Don't use these words in your programs: global persistent break continue error exit quitMAJOR points lost for using these in your programs!

  • *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

  • *An algorithmfor ???pick rand numberif oddIncrement odd counterelseIncrement even counterendend

    % Compute odd percentage% Compute even percentage% Print out results

    Note counters need to be INITIALIZED to 0. Before or in the loop?

  • *Solution% set up countersodd_cnt = 0;even_cnt = 0;

    %loop to create/analyze numbersfor cnt=1:200value = floor(rand()*100) + 1;if mod(value, 2) == 1 % odd numberodd_cnt = odd_cnt + 1;else % even numbereven_cnt = even_cnt + 1;endend

    %calculate/display resultsodd_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

  • *How long to generate random #'sWrite 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

  • *Final ProjectIntroduction

  • *Final ProjectThe descriptions provided here are only acting as summaries please see the complete description on your section's website.

    GoalCreate 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.

  • *Final Project, cont.While all topics contribute to the grading of the project, heavy emphasis is assigned to the proper use of:

    AlgorithmComplexity and efficiencyProgrammer-defined functionsLoopsFile I/O

  • *Final Project, cont.

    Connect 4Hunting DatabaseMP3 playerKeyboard DDRDrum HeroWill a beam break?Fuel efficiency and gas costBall and wall collisionAutomatic toll systemForces in a car crashElectrical circuit analysisExamples of past projects:Audio AnalysisSerial Port IMThermistor Data CollectionBezier Curve FitUnit ConversionTournament GenerationDeal or No DealLoad and moment distribution on a beam w/ plottingCaptain's Jack Sparrow'smagical compass

  • *Final Project, cont.Possible areas for new projects:

    GenealogyThermodynamicsComputational Fluid DynamicsImage / Visual ProcessingModel Rocket / RC Plane Telemetry2D / 3D environment modelingOrbital Mechanics

  • *Final Project, cont.Extra Credit is provided for:

    Innovative project concepts

    Advanced programming techniques

    Exceptional program development

  • *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.

  • *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


View more >