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
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

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
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Decision-Making Programs
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Programming with MATLAB
Chapter 1 Computing Tools Data Representation, Accuracy and Precision Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction.
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.
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.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Thursday, December 14, 2006 “Would you tell me, please, which way I ought to go from here?” “That depends a good deal on where you want to get to,” said.
Chapter 4: Control Structures: Selection
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Programming with MATLAB. Relational Operators The arithmetic operators has precedence over relational operators.
1 Chapter 4 Simple Selections and Repetitions INTRODUCTION The majority of challenging and interesting algorithms necessitate the ability to make.
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.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 8 Linear Algebraic Equations PowerPoint to accompany Copyright © 2010.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 4 Programming with MATLAB PowerPoint to accompany Copyright © The.
Chapter 2 - Algorithms and Design
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
CSE123 Lecture 3 Different types of Variables Logical operators, Conditional Statements and If Blocks.
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.
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.
ENGR-25_Programming-3.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Licensed Electrical.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
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. 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 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
CSE123 Lecture 3 Files and File ManagementScripts.
Structured Programming I – Relational & Logical Operators Objectives: By the end of this class you should be able to: Change graph interactively in EXCEL.
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.
1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else.
Conditional Statements.  Quiz  Hand in your jQuery exercises from last lecture  They don't have to be 100% perfect to get full credit  They do have.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Introduction to MATLAB 7
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.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
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. Introduction to MATLAB 7 for Engineers William J. Palm.
The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development Lecture 2 Debugging,
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.
1 Structured Programming EEN170 Programming in MATLAB.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Relational and Logical Operators EE 201 1C7-2 Spring 2012.
Introduction to MATLAB for Engineers, Third Edition
Chapter 4 MATLAB Programming
Matlab Basics.
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 4 Programming with MATLAB PowerPoint to accompany

This Week's Agenda Problem Solving with logic Problem Solving with logic Relational and logical operators Relational and logical operators Array/Vector selection operations Array/Vector selection operations using relational and logical operators using relational and logical operators using find( ) using find( ) If and if-else statements on Scalar Data If and if-else statements on Scalar Data

Relational operators Table 4.2–1 Operator Meaning < Less than. <= Less than or equal to. > Greater than. >= Greater than or equal to. == Equal to. ~= Not equal to. 1 means “true” 0 means “false” 4-19

Relational Operators on scalars only give one result: 1 or 0

Relational Operators on Vectors can also be useful For example, suppose that x = [6,3,9] and y = [14,2,9] The following MATLAB session shows some examples. >>z = (x < y)‏ z = >>z = (x ~= y)‏ z = >>z = (x > 8)‏ z =

Try it out...

A twist...how to count the number of “trues” ? (you already know one way...) ‏ Hint: use sum( )

Picking out certain cells using R.O.s The relational operators can be used for array addressing. For example, with x = [6,3,9] and y = [14,2,9], typing z = x(x<y)‏ finds all the elements in x that are less than the corresponding elements in y. The result is z = 6. length(z) OR length(x(x<y)) will tell how many “trues” 4-21 Another way...

This is called Accessing Arrays Using Logical Arrays When a logical array is used to address another array, it extracts from that array the elements in the locations where the logical array has 1s. So typing A(B), where B is a logical array of the same size as A, returns the values of A at the indices where B is (continued …)‏

OperatorNameDefinition ~ NOT ~A returns an array the same dimension as A ; the new array has ones where A is zero and zeros where A is nonzero. & AND A & B returns an array the same dimension as A and B ; the new array has ones where both A and B have nonzero elements and zeros where either A or B is zero. | OR A | B returns an array the same dimension as A and B ; the new array has ones where at least one element in A or B is nonzero and zeros where A and B are both zero need more precision? try the "Logical operators" Table 4.3–1 (continued …)‏

Some logical examples Example 1 y=[1 2 3]; y<6 ( ans = 1 1 1) ‏ y 0 (ans = 1 1 1) ‏ y 0 (ans = 1) ‏ because all cells satisfy because all cells satisfy Example 2 y=[1 2 3]; y<3 (ans = 1 1 0) ‏ y =3 (ans= 1 0 1) ‏ y = 3 ( ans= 0) because all don't satisfy because all don't satisfy

Try it out... xor(A,B) Returns an array with ones where either A or B is nonzero, but not both, and zeros where A and B are either both nonzero or both zero.

A real application......to solve on your own!

PrecedenceOperator type FirstParentheses; evaluated starting with the innermost pair. SecondArithmetic operators and logical NOT (~); evaluated from left to right. ThirdRelational operators; evaluated from left to right. FourthLogical AND. FifthLogical OR Order of precedence for operator types. Table 4.3–2

The find Function – THIS IS COOL find(A)‏ [u,v,w] = find(A)‏ Computes an array containing the indices of the nonzero elements of the array A. Computes the arrays u and v containing the row and column indices of the nonzero elements of the array A and computes the array w containing the values of the nonzero elements. The array w may be omitted. 4-33

Logical Operators and the find Function Consider the session >>x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7]; >>z = find(x&y)‏ z = Note that the find function returns the indices, and not the values (continued …)‏

Logical Operators and the find Function (continued)‏ Remember, the find function returns the indices, and not the values. In the following session, note the difference between the result obtained by y(x&y) and the result obtained by find(x&y) in the previous slide. >>x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7]; >>values = y(x&y)‏ values = >>how_many = length(values)‏ how_many = More? See pages

One last logical problem… find can help you

The need for IF The relational and logical operators can solve many vector related logical problems Sometimes we need to select/execute different groups of statements in our program depending on the value of a scalar (or values in a vector)‏ This is where IF statements come in...

Different kinds of IF One Choice selection (if) (do/don’t do) Two Way selection (if-else) (either/or) Multi-Way selection (if-elseif...else)‏ Nested selection (infinite possibilities)

The Simplest if Statement The if statement’s basic form is if logical expression statements end Every if statement must have an accompanying end statement. The end statement marks the end of the statements that are to be executed if the logical expression is true More? See pages

22 For Example Consider this …. You get an award only if you get a perfect score on a test if score == 100 disp('Congratulations!')‏ end

23 Simple if Selection Flowchart true false CONGRATS! Next statement score==100

The if- else Statement (Two-way) The basic structure for the use of the if- else statement is if logical expression statement group 1 else statement group 2 end 4-37 More? See pages

Flowchart of the if- else structure. Figure 4.4–2 4-38

26 if-else (Two-way) Example To calculate hourly wages there are two choices Regular time ( up to 40 hours)‏ gross_pay = rate * hours; Overtime ( over 40 hours) gets $50 bonus gross_pay = rate * ; The program must choose which of these expressions to use

27 Paycheck Flowchart (if-else) ‏ Paycheck Flowchart (if-else) ‏ hours>40 truefalse calc pay with overtime calc pay regular display pay to screen

28 Designing the Conditional Determine if hours >40 is true If it is true, then use gross_pay = rate * If it is not true, then use gross_pay = rate * hours

29 Coding the Branch The actual MATLAB code to do this: if hours > 40 gross_pay = rate * else gross_pay = rate * hours end Notice, one condition, for two statements Notice: no condition here! “else” means “condition was false”

30 Full Application: Calculating Pay %This program calculates pay based on % hours worked and pay rate hours=input('enter hours'); rate=input('enter rate'); if hours > 40 pay = rate * else pay = rate * hours end

CAUTION When the test, if logical expression, is performed, where the logical expression may be an array, the test returns a value of true only if all the elements of the logical expression are true! 4-39

For example, if we fail to recognize how the test works, the following statements do not perform the way we might expect. x = [4,-9,25]; if x < 0 disp(’Some elements of x are negative.’)‏ else y = sqrt(x)‏ end Because the test if x < 0 is false, when this program is run it gives the result y = i5 4-40

Instead, consider what happens if we test for x positive. x = [4,-9,25]; if x >= 0 y = sqrt(x)‏ else disp(’Some elements of x are negative.’)‏ end When executed, it produces the following message: Some elements of x are negative. The test if x = 0 also returns a false value because x >= 0 returns the vector [1,0,1]. 4-41

Use Those Logical Operators... The following statements if logical expression 1 if logical expression 2 statements end can be replaced with the more concise program if logical expression 1 & logical expression 2 statements end 4-42

The if- elseif...else Statement (Multi-way branch) The most general form of the if statement is if logical expression 1 statement group 1 elseif logical expression 2 statement group 2 [any number of elseif may be included here] else statement group n end The else and elseif statements may be omitted if not required. However, if both are used, the else statement must come after the elseif statement to take care of all conditions that might be unaccounted for. 4-43

Flowchart for the general if- elseif-else structure. Figure 4.4–3 4-44

For example, suppose that y = log(x) for x > 10, y = sqrt(x) for 0 <= x <= 10, and y = exp(x) - 1 for x < 0. The following statements will compute y (assuming x already has a scalar value assigned). if x > 10 y = log(x)‏ elseif x >= 0 y = sqrt(x)‏ else y = exp(x) - 1 end 4-45 More? See pages

Dive In! Use the multi-way if… type “help mod” for info Start with a simple script file, then convert it to a function named leapYear

Nesting More complicated problems require nesting conditionals within conditionals There is no limit to how many levels of nesting you can use

Flowchart illustrating nested if statements. Figure 4.4–44-46

Code for previous flowchart use indenting to clarify structure x=input('Enter x'); if x>10 y=log(x); if y>=3 z=4*y; elseif y>=2.5 z=2*y; else z=0; end else y=5*x; z=7*x; end

Figure P

Problem 19 continued

Strings [ NOT USEFUL FOR TODAY] A string is a variable that contains characters. Strings are useful for creating input prompts and messages and for storing and operating on data such as names and addresses. To create a string variable, enclose the characters in single quotes. For example, the string variable name is created as follows: >>name = ’Leslie Student’ name = Leslie Student 4-47 (continued …)‏

Strings (continued)‏ The following string, number, is not the same as the variable number created by typing number = 123. >>number = ’123’ number =

Strings and the input Statement The prompt program on the next slide uses the isempty(x) function, which returns a 1 if the array x is empty and 0 otherwise. It also uses the input function, whose syntax is x = input(’prompt’, ’string’)‏ This function displays the string prompt on the screen, waits for input from the keyboard, and returns the entered value in the string variable x. The function returns an empty matrix if you press the Enter key without typing anything. 4-49

Strings and Conditional Statements The following prompt program is a script file that allows the user to answer Yes by typing either Y or y or by pressing the Enter key. Any other response is treated as the answer No. response = input(’Want to continue? Y/N [Y]: ’,’s’); if (isempty(response))|(response==’Y’)|(response==’y’)‏ response = ’Y’ else response = ’N’ end 4-50 More? See pages