This is the basis for the programming concept called a loop statement

Similar documents
MATLAB provides several built-in statements that allow for conditional behavior if/elseif/else switch menu

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

REPETITIVE EXECUTION: LOOPS

Flow Control: Branches and loops

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Chapter 4: Programming with MATLAB

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Loop Statements and Vectorizing Code

Programming for Experimental Research. Flow Control

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

Repetition Structures Chapter 9

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

LOOPS. Repetition using the while statement

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

Branches, Conditional Statements

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

ECE 102 Engineering Computation

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Score score < score < score < 65 Score < 50

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

CSC 101: Lab Manual#9 Machine Language and the CPU (largely based on the work of Prof. William Turkett) Lab due date: 5:00pm, day after lab session

Unit 7. 'while' Loops

Lab 5 - Repetition. September 26, 2018

Module 4: Decision-making and forming loops

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Introduction to Computer Programming for Non-Majors

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C/C++ Programming for Engineers: Matlab Branches and Loops

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

C H A P T E R 1. Introduction to Computers and Programming

Information Science 1

If Statements, For Loops, Functions

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

To become familiar with array manipulation, searching, and sorting.

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Writing MATLAB Programs

Decision Making in C

Selection Statements. Chapter 4. Copyright 2013 Elsevier Inc. All rights reserved 1

8. Control statements

Chapter Goals. Contents LOOPS

3 The L oop Control Structure

CSCE 206: Structured Programming in C++

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

Quiz 1: Functions and Procedures

Our Strategy for Learning Fortran 90

5. Control Statements

Advanced Computer Programming

7 Control Structures, Logical Statements

CS 177 Recitation. Week 1 Intro to Java

Topics. Hardware and Software. Introduction. Main Memory. The CPU 9/21/2014. Introduction to Computers and Programming

Other Loop Options EXAMPLE

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Condition Controlled Loops. Introduction to Programming - Python

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Loop structures and booleans

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Unit E Step-by-Step: Programming with Python

Computer Programming ECIV 2303 Chapter 6 Programming in MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

APPM 2460: Week Three For, While and If s

Chapter 4: Control structures. Repetition

Information Science 1

Loops. by Ahmet Sacan

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Text Input and Conditionals

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Introduction to programming in MATLAB

MATLAB. Devon Cormack and James Staley

Lecture 10. Daily Puzzle

Java Bytecode (binary file)

Lecture 10: for, do, and switch

CS 231 Data Structures and Algorithms, Fall 2016

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Pace University. Fundamental Concepts of CS121 1

MITOCW watch?v=0jljzrnhwoi

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 4: Control structures

Chapter 3: Program Statements

bool bool - either true or false

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

STUDENT LESSON A12 Iterations

(Python) Chapter 3: Repetition

Time-Saving Hint: Use the up-arrow on your keyboard to cycle through old commands.

Decisions, Decisions. Testing, testing C H A P T E R 7

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

function [s p] = sumprod (f, g)

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Transcription:

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 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 for loopvar = range action(s) end

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 reallocated 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 preallocates 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 The outer loop. loopvar1 is iterated over range1 The inner loop. loopvar2 is iterated over range2 for loopvar1 = range1 for loopvar2 = range2 action(s) end end

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 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). while condition action(s) end

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?