Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.

Slides:



Advertisements
Similar presentations
Flow Charts, Loop Structures
Advertisements

CMPS 1371 Introduction to Computing for Engineers
CS0004: Introduction to Programming Repetition – Do Loops.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
MatLab – Palm Chapter 4, Part 3 For and While Loops
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Chapter 2: Input, Processing, and Output
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 6 - VB 2005 by Schneider1 Chapter 6 – Repetition 6.1 Do While and Do Until Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Copyright © 2006 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 1 Chapter 2.
Computer Science 12 Mr. Jean May 2 nd, The plan: Video clip of the day Review of common errors in programs 2D Arrays.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
9-1 COBOL for the 21 st Century Nancy Stern Hofstra University Robert A. Stern Nassau Community College James P. Ley University of Wisconsin-Stout (Emeritus)
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
6.2 For…Next Loops General Form of a For…Next Loop
Working with Arrays in MATLAB
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical.
ENG College of Engineering Engineering Education Innovation Center 1 Basic For Loops in MATLAB Programming in MATLAB / Chapter 6 Topics Covered:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 7 Problem Solving with Loops
Decision Making and Branching (cont.)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Chapter 4 MATLAB Programming MATLAB Troubleshooting Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7.
1 Structured Programming EEN170 Programming in MATLAB.
CSE123 - Lecture 4 Structured Programming- Loops.
EE 201 1C10-2 Spring 2012 LOOPS For.  Achieve Comprehension LOL of using Loops in programming. Class Learning Objectives 2C10-2 Spring 2012.
Chapter 1 Computing Tools Variables, Scalars, and Arrays Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Copyright © The McGraw-Hill Companies, Inc. This work is only for non-profit use by instructors in courses for which this textbook has been adopted.
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
Chapter 2: Input, Processing, and Output
Quick Test What do you mean by pre-test and post-test loops in C?
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
Iteration: Beyond the Basic PERFORM
Types of Flow of Control
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Chapter 2: Input, Processing, and Output
Chap 7. Advanced Control Statements in Java
LOOPS For EE 201 C10-1 SPRING 2012.
REPETITION Why Repetition?
Presentation transcript:

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 4B Programming LOOPS with MATLAB PowerPoint to accompany

Agenda For Loops and Common Tasks For Loops and Common Tasks Finding the max using a For loop Finding the max using a For loop Nested For Loops Nested For Loops While Loops While Loops

Why Loops? In Chapter 4 you learned a number of powerful MATLAB features for processing arrays In Chapter 4 you learned a number of powerful MATLAB features for processing arrays x(x>5) shows all x cells that are larger than 5 x(x>5) shows all x cells that are larger than 5 How does this work? A built in loop visits each cell How does this work? A built in loop visits each cell These are great time-saving features These are great time-saving features Some problems are more complex and require explicitly writing our own loops to solve them Some problems are more complex and require explicitly writing our own loops to solve them The “old fashioned” way programmers used to work The “old fashioned” way programmers used to work More flexibility (and sometimes clarity) in formulating solutions More flexibility (and sometimes clarity) in formulating solutions

for Loops A simple example of a for loop is for k = 5:10:35 x = k^2 end The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each successive pass through the loop increments k by 10 and calculates x until k exceeds 35. Thus k takes on the values 5, 15, 25, and 35, and x takes on the values 25, 225, 625, and The program then continues to execute any statements following the end statement. 4-51

Flowchart of a for Loop. Figure 4.5–1 4-52

Note the following rules when using for loops with the loop variable expression k = m:s:n: The step value s may be negative. Example: k = 10:-2:4 produces k = 10, 8, 6, 4. If s is omitted, the step value defaults to 1. If s is positive, the loop will not be executed if m is greater than n. If s is negative, the loop will not be executed if m is less than n. If m equals n, the loop will be executed only once. If the step value s is not an integer, round-off errors can cause the loop to execute a different number of passes than intended. 4-53

Common Tasks: Making an Array Loops can create arrays for you: Loops can create arrays for you: for k = 1:10 x(k) = k;  cell #1 gets 1, #2 gets 2... y(k)= k^2;  k is a scalar so no '.' needed y(k)= k^2;  k is a scalar so no '.' neededendplot(x,y); Same as: x=[1:10]; y=x.^2; plot(x,y) Same as: x=[1:10]; y=x.^2; plot(x,y)

Q: What values are in y? d) for k = 1:11 y(k)= (k-1)*0.2; y(k)= (k-1)*0.2; end end b) for k = 1:11 y(k)= 11 – k; y(k)= 11 – k; end end a) for k = 1:10 y(k)= k*10; y(k)= k*10; end end c) for k = 1:5 y(k)= k*10-100; y(k)= k*10-100; end end

Common Tasks: Accessing an Array Loops can also sample data from the cells of a pre-existing array. Suppose: Loops can also sample data from the cells of a pre-existing array. Suppose: hours=[40, 65, 48, 30, 20]; hours=[40, 65, 48, 30, 20]; totalOvertime = 0; totalOvertime = 0; for k = 1:length(hours) for k = 1:length(hours) if hours(k) > 40 totalOvertime=totalOvertime + hours(k) - 40; totalOvertime=totalOvertime + hours(k) - 40; end endend totalOvertime (result is 33)

Common Task: Finding the Maximum The easy way: The easy way: [max, n] = max(hours) The hard(er) way: The hard(er) way: We can also do this using a loop We can also do this using a loop With or without a vector With or without a vector Again, we get more flexibility for certain calculations Again, we get more flexibility for certain calculations

Finding the max…core idea max=0; // make a variable to hold max num=input(‘enter a number’); Core idea Core idea Compare num with max… Compare num with max… if num>max max=num; max=num;end 11

Finding the max…put in a loop max=0; index=0; for i=1:5 for i=1:5 num=input(‘enter a number’); num=input(‘enter a number’); if num > max if num > max max = num; max = num; end end max max 12

Finding the max…of a vector max=0; hours=[40, 65, 48, 30, 20]; hours=[40, 65, 48, 30, 20]; for i=1:length(hours) for i=1:length(hours) if hours(i) > max if hours(i) > max max = hour(i); max = hour(i); max_cell = i;  capture cell number max_cell = i;  capture cell number end end disp('max = '); disp(max); disp('max = '); disp(max); disp(' at cell # '); disp(index); disp(' at cell # '); disp(index); 13

1) Finding the min…application 1) create a for loop with t going 0:0.01:4 2) calculate scalar x and y for each t 3) calculate distance, check for min, and save index of min inside loop 4) then show minT and minD

while Loops The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance. A simple example of a while loop is x = 5; while x < 25 disp(x) x = 2*x - 1; end The results displayed by the disp statement are 5, 9, and

The typical structure of a while loop follows. while logical expression statements end For the while loop to function properly, the following two conditions must occur: 1.The loop variable must have a value before the while statement is executed. 2. The loop variable must be changed somehow by the statements. 4-58More? See pages

Flowchart of the while loop. Figure 4.5–3 4-59

A simple example of a while loop is x = 5;k = 0; while x < 25 k = k + 1; y(k) = 3*x; x = 2*x-1; end The loop variable x is initially assigned the value 5, and it keeps this value until the statement x = 2*x - 1 is encountered the first time. Its value then changes to 9. Before each pass through the loop, x is checked to see if its value is less than 25. If so, the pass is made. If not, the loop is skipped. 4-60

Homework #2 Ulam Sequence The Ulam Sequence The Ulam Sequence A mathematician named Ulam proposed generating a sequence of numbers from any positive integer n (n > 0) as follows: If n is 1, stop. If n is even, the next number is n/2. If n is odd, the next number is 3*n + 1. Continue with this process until reaching 1. Here are some examples for the first few integers. 2 -> 1 2 -> 1 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 4 -> 2 -> 1 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1

Tracing a Loop Hand tracing is a great way to debug a loop Make a table of all the variables Update table as program changes variables

Tracing a Loop (example) n = 1; y=20; sum = 0; while (n <= y) sum = sum + n*y; n = n + 2; y = y/2; end Sumny done

Using Nested Loops

3) An optimization problem we need a way to check all possibilities Problem simplified from text

Hints for # 3 The range of possible TVs: 0 to 300 (why? – check inventory) The range of possible TVs: 0 to 300 (why? – check inventory) Range of possible speakers? Range of possible speakers? Lots of permutations! Lots of permutations! If we have a vector p = [ numTV numSpkr]; If we have a vector p = [ numTV numSpkr]; And a vector unit_cost=[ 80 40]; And a vector unit_cost=[ 80 40]; Then profit = unit_cost*p'; Then profit = unit_cost*p'; Q: How do we cover all permutations??? Q: How do we cover all permutations???

Hints for #3, continued A: Nested For Loops A: Nested For Loops for numTV = 1:300 for numSpkr = 1: ?? for numSpkr = 1: ?? p = [ numTV numSpkr] p = [ numTV numSpkr] profit = … etc… profit = … etc… also, check sufficient inventory for p end endend