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
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Flow Charts, Loop Structures
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
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.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 2: Input, Processing, and Output
©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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 8 Linear Algebraic Equations PowerPoint to accompany Copyright © 2010.
For Loops 2 ENGR 1181 MATLAB 9. For Loops and Looped Programming in Real Life As first introduced last lecture, looping within programs has long been.
Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 4 Programming with MATLAB PowerPoint to accompany Copyright © The.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical.
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.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL 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.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 4 Programming with MATLAB. Algorithms and Control Structures Algorithm: an ordered sequence of precisely defined instructions that performs some.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical.
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.
Matlab Programming for Engineers
ENG College of Engineering Engineering Education Innovation Center 1 Basic For Loops in MATLAB Programming in MATLAB / Chapter 6 Topics Covered:
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.
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. Introduction to MATLAB 7 for Engineers William J. Palm.
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 © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
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.
1 Matlab for Engineering Applications Introduced by Jen-Yang Chen Department of Electronic Engineering Ming Chuan University.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
1 Structured Programming EEN170 Programming in MATLAB.
CSE123 - Lecture 4 Structured Programming- Loops.
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.
Introduction to MATLAB for Engineers, Third Edition
מטלב וניתוח נתונים ממערכות עצביות היכרות עם MATLAB
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
Matlab Training Session 4: Control, Flow and Functions
Chapter 4 MATLAB Programming
Types of Flow of Control
MatLab – Palm Chapter 4, Part 2 The if and switch structure
MatLab – Palm Chapter 4, Part 2 The if and switch structure
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.
Chap 7. Advanced Control Statements in Java
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 Switch statement Switch statement

Why Loops? In Chapter 3 you learned a number of powerful MATLAB features for processing arrays In Chapter 3 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)

Easy… 1) create t and vs using vector notation 2) create VL using loop and if

Problem 24 continued

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 13

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 14

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); 15

Finding the min…application 1) create t, x and y using vector notation 2) make a loop for k=1: length(t) 3) calculate distance, check for min, and save index of min inside loop 4) then show t(min) and minDist

Write a function, make a graph… this function only takes scalars

Problem 22 continued

MISCELLANEOUS The continue Statement The following code uses a continue statement to avoid computing the logarithm of a negative number. x = [10,1000,-10,100]; y = NaN*x; for k = 1:length(x) if x(k) < 0 continue end y(k) = log10(x(k)); end y The result is y = 1, 3, NaN, More? See pages

MISCELLANEOUS Use of a Mask We can often avoid the use of loops and branching and thus create simpler and faster programs by using a logical array as a mask that selects elements of another array. Any elements not selected will remain unchanged. The following session creates the logical array C from the numeric array A given previously. >>A = [0, -1, 4; 9, -14, 25; -34, 49, 64]; >>C = (A >= 0); The result is C =

We can use this mask technique to compute the square root of only those elements of A given in the previous program that are no less than 0 and add 50 to those elements that are negative. The program is A = [0, -1, 4; 9, -14, 25; -34, 49, 64]; C = (A >= 0); A(C) = sqrt(A(C)) A(~C) = A(~C) More? See pages

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

Hints for # 27 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 27, 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

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

Another Example of a while Loop Write a script file to determine how many terms are required for the sum of the series 5k 2 – 2k, k = 1, 2, 3, … to exceed 10,000. What is the sum for this many terms? total = 0;k = 0; while total < 1e+4 k = k + 1; total = 5*k^2 - 2*k + total; end disp(’The number of terms is:’) disp(k) disp(’The sum is:’) disp(total) The sum is 10,203 after 18 terms. 4-61

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

Tracing (homework problem)

The Editor/Debugger containing two programs to be analyzed. Figure 4.7–1 4-65More? See pages

The switch Structure The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structure. 4-62

Syntax of the switch structure switch input expression (which can be a scalar or string). case value1 statement group 1 case value2 statement group 2. otherwise statement group n end 4-63

The following switch block displays the point on the compass that corresponds to that angle. switch angle case 45 disp(’Northeast’) case 135 disp(’Southeast’) case 225 disp(’Southwest’) case 315 disp(’Northwest’) otherwise disp(’Direction Unknown’) end 4-64More? See pages

How to input type of materials? Introducing…text variables!

This uses your leap year function This uses your leap year function (prob18 from assignment 4) For example input For example input it says this is day number 61 it says this is day number 61 (31 for Jan + 28 for Feb + 2 for Mar) (31 for Jan + 28 for Feb + 2 for Mar) for dates > Feb 28 you have to add leapYear return value (0 for no LY or 1 for leap year)