Chapter Chapter 4. Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times.

Slides:



Advertisements
Similar presentations
Programming Logic and Design Eighth Edition
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS0004: Introduction to Programming Repetition – Do Loops.
Programming Logic and Design, Third Edition Comprehensive
Repeating Actions While and For Loops
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Computer Science 1620 Loops.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Pseudocode and Algorithms
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
CPS120 Introduction to Computer Science Iteration (Looping)
Programming Logic and Design Fifth Edition, Comprehensive
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 13 Conditional.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
CPS120 Introduction to Computer Science Iteration (Looping)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 13 Conditional.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Chapter 4 Repetition Statements (loops)
Repetition Structures Chapter 9
ESS 116 Introduction to Data Analysis in Earth Science
Topics Introduction to Repetition Structures
Python: Control Structures
Programming Logic and Design Fourth Edition, Comprehensive
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Loop Structures.
Topics Introduction to Repetition Structures
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Outline Altering flow of control Boolean expressions
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
3.5- The while Statement The while statement has the following syntax:
Loop Statements & Vectorizing Code
Topics Introduction to Repetition Structures
Repetition Statements (Loops) - 2
Selection Statements Chapter 3.
Loop Statements & Vectorizing Code
Chapter 13 Conditional Repetition
Presentation transcript:

Chapter Chapter 4

Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times did you solve it? What if you had millions of data points that had to be processed using the same solution? Only need to solve it once Tell the computer to repeat n-times This is the basis for the programming concept called a loop statement

MATLAB provides two types of loops A counted loop “for” Used when you know ahead of time how many times some action will be repeated Repeat n-times A conditional loop “while” Used when you do not know ahead of time how many times some action will be repeated Repeat until some logical statement becomes false

Used with a pre-defined number of iterations of the loop variable for loopVar = range action(s) end The “for” keyword (“for” is a reserved word in MATLAB) The loop variable, which can be any valid variable name Traditionally, we use i, j, k, or other single letters The range or list of values the loopVar will take on Can be any vector, but typically the colon operator is used The action(s) that will be performed during each iteration The “end” keyword. Signifies that the code should go back to beginning of the loop statement if more iterations remain

Lets make a simple for loop to see how everything works During each iteration Loop variable i is changed i is printed using fprintf Note that the actions must be indented Makes code easier to read MATLAB editor does this automatically

The loop variable can change by any increment Most commonly the increment is 1

The loop variable can have positive or negative values Most commonly values are positive After loop is complete Can still use the loop variable Has the final value of the loop

The loop iterations can be defined by any vector This is not typical Whenever possible, use the colon operator

A common use of a loop: perform an operation on each and every data point, one by one. Doesn’t matter how many data points there are* *Obviously, there is some limit based on your computer’s RAM, CPU speed, and operating system

Lets mimic the behavior of the MATLAB function “sum” Use a for loop

Because MATLAB code is interpreted on the fly (i.e. not compiled into binary exe files) Each time the loop restarts, the whole loop must be compiled again Chapter 5 will cover ways to avoid using loops (vectorization) For most operations, loops are still fast enough Each time an entry is added to a matrix, the whole matrix must be recreated

To calculate execution times of scripts, MATLAB provides a timer function “tic” starts the timer “toc” stops the timer and prints the total execution time to the command window Makes most sense to use in scripts/functions Using tic toc, we can determine if code is efficient

Each time the loop iterates... velKmHr is completely re- allocated and remade each iteration This is why the editor gives a warning orange wiggly line

Each time the loop iterates... One entry in velKmHr is overwritten The whole matrix doesn’t need to be remade

Numerical results are identical Second script pre- allocates the velKmHr variable Runs > 5x faster!!! The Take-Home Message: While most operations are very fast, pre-allocating a matrix is easy, so you should always do it (if possible)

A loop to find the maximum of a vector Can also be accomplished with the command “max” Which do you think is faster?

We can combine loops with Boolean logic to test if each entry meets some criterion Make sure that all of your indenting is consistent. MATLAB’s editor should do this automatically

We can combine loops with Boolean logic tests Can we pre-allocate “newData”?

We can nest “for” loops into inner and outer loops Can also be done with “while” loops Often useful for dealing with 2D data for loopVar1 = range1 for loopVar2 = range2 action(s) end The outer loop. “loopVar1” is iterated over “range1” The inner loop. “loopVar2” is iterated over “range2”

Lets try a simple nested for loop.

Lets try another simple nested for loop. This can be very handy for making a grid of data points A common task in any quantitative science

This is NOT the way to do it! Lets try a nested for loop

To make a 2D grid we need a nested for loop Outer loop: x-range; Inner loop: y-range Could even make spherical grids (r, θ, ϕ)

The “for” loop is a counted loop You must know the number of iterations beforehand What if you don’t know how many iterations there will be? Use a conditional loop: the “while” loop Loop continues until some condition is no longer met Often paired with counter variables (to keep track of iterations) Can be used to error check, or only read part of a dataset. Most for loops can also be written as while loops Do whichever one is easiest to understand Typically for loops require less code

Used with a conditional test of the loop variable while condition action(s) end The “while” keyword (“while” is a reserved word in MATLAB) A conditional statement to be tested at the beginning of each loop iteration. If true, loop continues, if false, loop ends The action(s) performed only if the condition(s) is “true” The “end” keyword. At this point, the computer goes back to the beginning of the while loop and re-tests the condition(s).

Tests if x < 8 If true: Prints out x to command window If false: Loop terminates

Can test more than one condition in a while loop Tests if x < 8 or y < 33

Make sure the condition tested will become false eventually If condition tested is never false: An infinite loop Kill by typing ctrl+c May take several tries What should be added?

If you use a while loop to read though a matrix/vector The whole matrix/vector may not be read Sometimes this is desired To test which data meets some condition for all data Use a for loop + if statement(s) Why does a while loop work here?

If we require input from the user The user may input incorrect/invalid data A while loop can check this

Loops allow us to solve a problem once Tell the computer to repeat n-times While modern computers are VERY fast… MATLAB is not efficient with loops* * (not true for most other languages) The whole loop is recompiled with each iteration Adding entries to end of a matrix is inefficient* *(overwriting is fast) You should pre-allocate matrices/vectors whenever possible Multiple loops can be nested Can nest a for and while loop Can nest if-elseif-else statements in a loop(s) When nesting anything, always consistently indent If loops are not fast in MATLAB, what can I do? Vectorize your code!! Anyone up for a game?