Matlab for Engineers Logical Functions and Control Structures Chapter 8.

Slides:



Advertisements
Similar presentations
RAPTOR Syntax and Semantics By Lt Col Schorsch
Advertisements

Flow Charts, Loop Structures
CMPS 1371 Introduction to Computing for Engineers
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
ITEC113 Algorithms and Programming Techniques
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Structured Program Development in C
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
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.
The University of Texas – Pan American
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
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.
Chapter 2 - Algorithms and Design
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Chapter 4 Selection Structures: Making Decisions.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
Linux Operations and Administration
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.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
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.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Introduction to Problem Solving and Control Statements.
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
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 tutorial course Lesson 4: Writing your own functions: programming constructs
Chapter 7 Problem Solving with Loops
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Controlling Program Flow with Decision Structures.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Finishing up Chapter 5. Will this code enter the if statement? G=[30,55,10] if G
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
REPETITION CONTROL STRUCTURE
Repetition Structures Chapter 9
Matlab Training Session 4: Control, Flow and Functions
CS1371 Introduction to Computing for Engineers
The Selection Structure
Scripts & Functions Scripts and functions are contained in .m-files
Programming Fundamentals
MATLAB: Structures and File I/O
User Defined Functions
Lecture 2: Logical Problems with Choices
Structured Program
Iteration: Beyond the Basic PERFORM
Introduction to Problem Solving and Control Statements
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 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Structural Program Development: If, If-Else
Presentation transcript:

Matlab for Engineers Logical Functions and Control Structures Chapter 8

Matlab for Engineers In this chapter we’ll introduce the… relational and logical operators find function if/else family of commands switch/case structure for and while loops

Matlab for Engineers Structures Sequence Selection Repetition SequenceSelectionRepetition (Loop)

Matlab for Engineers Sequence and Repetition structures require comparisons to work Relational operators make those comparisons Logical operators allow us to combine the comparisons

Matlab for Engineers Relational Operators < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to

Matlab for Engineers Comparisons are either true or false Most computer programs use the number 1 for true and 0 for false The results of a comparison are used in selection structures and repetition structures to make choices

Matlab for Engineers Matlab compares corresponding elements and determines if the result is true or false for each

Matlab for Engineers In order for Matlab to decide a comparison is true for an entire matrix, it must be true for every element in the matrix

Matlab for Engineers Logical Operators & and ~ not | or xor exclusive or

Matlab for Engineers Flow Charts and Pseudo- Code As you write more complicated programs it becomes more and more important to plan your code before you write it Flow charts – graphical approach Pseudo-code – verbal description

Matlab for Engineers Pseudo-code Outline a set of statements describing the steps you will take to solve a problem Convert these steps into comments in an M-file Insert the appropriate Matlab code into the file between the comment lines

Matlab for Engineers Pseudo-code Example You’ve been asked to create a program to convert miles/hr to ft/s. The output should be a table, complete with title and column headings

Matlab for Engineers Outline the steps Define a vector of mph values Convert mph to ft/s Combine the mph and ft/s vectors into a matrix Create a table title Create column headings Display the table

Matlab for Engineers Convert the steps to M-file comments

Matlab for Engineers Insert the Matlab code between the comments

Matlab for Engineers Flow Charting Especially appropriate for more complicated programs Create a big picture graphically Convert to pseudo-code

Matlab for Engineers Simple Flow Chart Symbols An oval indicates the beginning of a section of code A parallelogram indicates an input or output A diamond indicates a decision point Calculations are placed in rectangles

Matlab for Engineers Start Define a vector of miles/hour Calculate the ft/sec vector Combine into a table Create an output table using disp and fprintf End This flowchart represents the mph to ft/s problem

Matlab for Engineers Logical Functions Matlab offers traditional programing selection structures if if/else switch/case Series of logical functions that perform many of the same tasks

Matlab for Engineers find The find command searches a matrix and identifies which elements in that matrix meet a given criteria.

Matlab for Engineers For example… The US Naval Academy requires applicants to be at least 5’6” tall Consider this list of applicant heights 63”, 67”, 65”, 72”, 69”, 78”, 75” Which applicants meet the criteria?

Matlab for Engineers The find function returns the index number for elements that meet a criteria

Matlab for Engineers index numbers element values

Matlab for Engineers

You could use the disp and fprintf functions in this program to create a more readable report

Matlab for Engineers You could also make a table of those who do not meet the height requirement

Matlab for Engineers By combining relational and logical operators you can create fairly complicated search criteria Assume applicants must be at least 18 years old and less than 35 years old They must also meet the height requirement

Matlab for Engineers Applicant pool HeightAge Inchesyears

Matlab for Engineers Let’s use Pseudo-code to plan this program Create a 7x2 matrix of applicant height and age information Use the find command to determine which applicants are eligible Use fprintf to create a table of results

Matlab for Engineers This is the M-file program to determine who is eligible

Matlab for Engineers Because we didn’t suppress all the output, the intermediate calculations were sent to the command window

Matlab for Engineers The find command can return either… A single index number identifying an element in a matrix A matrix of the row numbers and the column numbers identifying an element in a matrix You need to specify two results if you want the row and column designation [row, col] = find( criteria)

Matlab for Engineers Imagine you have a matrix of patient temperature values measured in a clinic Station 1Station 2Station

Matlab for Engineers Use the find command to determine which patients have elevated temperatures These elements refer to the single index number identification scheme

Matlab for Engineers If we want the row and column… 1,11,21,3 2,12,22,3 3,13,23,3

Matlab for Engineers Using fprintf we can create a more readable report

Matlab for Engineers Flow charting and Pseudo- code for find Commands Start Define a vector of x values Find the index numbers in the x matrix for values greater than 9 Use the index numbers to find the x values Create an output table using disp and fprintf End %Define a vector of x values x=[1,2,3; 10, 5,1; 12,3,2;8, 3,1] %Find the index numbers of the values in %x >9 element = find(x>9) %Use the index numbers to find the x %values greater than 9 by plugging them %into x values = x(element) % Create an output table disp('Elements greater than 9') disp('Element # Value') fprintf('%8.0f %3.0f \n', [element';values'])

Matlab for Engineers

Section 8.4 Selection Structures Most of the time the find function should be used instead of an if However, there are certain situations where if is the appropriate process to use

Matlab for Engineers Simple if if comparison statements end For example…. if G<50 count = count +1; disp(G); end

Matlab for Engineers If statements Easy to interpret for scalars What does an if statement mean if the comparison includes a matrix? The comparison is only true if it is true for every member of the array

Matlab for Engineers Consider this bit of code G=[30,55,10] if G<50 count = count +1; disp(G); end The code inside the if statement is not executed, because the comparison is not true!!

Matlab for Engineers This statement is false because at least one of the elements in G has a value >= 50 The value of count remains unchanged, because the statements inside the if structure are not executed

Matlab for Engineers This statement is true because all of the elements in G are < 50 The value of count increments by 1, because the statements inside the if structure not executed

Matlab for Engineers The if/else structure The simple if triggers the execution of a block of code if a condition is true If it is false that block of code is skipped, and the program continues without doing anything What if instead you want to execute an alternate set of code if the condition is false?

Matlab for Engineers Block of code to excute if the comparison is true Comparison TrueFalse Block of code to excute if the comparison is false Flow chart of an if/else structure

Matlab for Engineers Use an if structure to calculate a natural log Check to see if the input is positive If it is, calculate the natural log If it isn’t, send an error message to the screen

Matlab for Engineers M-file Program

Matlab for Engineers Interactions in the Command Window

Matlab for Engineers The if/else/elseif structure Use the elseif for multiple selection criteria For example Write a program to determine if an applicant is eligible to drive

Matlab for Engineers Start if age<16 True Sorry – You’ll have to wait age<18 You may have a youth license age<70 True You may have a standard license True Drivers over 70 require a special license End elseif else

Matlab for Engineers

Always test your programs – making sure that you’ve covered all the possible calculational paths

Matlab for Engineers switch/case This structure is an alternative to the if/else/elseif structure The code is generally easier to read This structure allows you to choose between multiple outcomes, based on some criterion, which must be exactly true

Matlab for Engineers When to use switch/case The criterion can be either a scalar (a number) or a string. In practice, it is used more with strings than with numbers.

Matlab for Engineers switch variable case option1 code to be executed if variable is exactly equal to option 1 case option2 code to be executed if variable is exactly equal to option 2 … case option_n code to be executed if variable is exactly equal to option n otherwise code to be executed if variable is not equal to any of the options end The structure of switch/case

Matlab for Engineers Suppose you want to determine what the airfare is to one of three cities

Matlab for Engineers

You can tell the input command to expect a string by adding ‘s’ in a second field.

Matlab for Engineers

Menu The menu function is often used in conjunction with a switch/case structure. This function causes a menu box to appear on the screen with a series of buttons defined by the programmer. input = menu(‘Message to the user’,’text for button 1’,’text for button 2’, etc)

Matlab for Engineers Because the input is controlled by a menu box, the user can’t accidentally enter a bad choice This means you don’t need the otherwise portion of the switch/case structure

Matlab for Engineers Note that the otherwise portion of the switch/case structure wasn’t used

Matlab for Engineers When you run this code a menu box appears Instead of entering your choice from the command window, you select one of the buttons from the menu

Matlab for Engineers If I select Honolulu…

Matlab for Engineers Section 8.5 Repetition Structures - Loops Loops are used when you need to repeat a set of instructions multiple times Matlab supports two types of loops for while

Matlab for Engineers When to use loops In general loops are best used with scalars Many of the problems you may want to attempt with loops can be better solved by vectorizing your code or with Matlab’s logical functions such as find

Matlab for Engineers For Loops for index = [matrix] commands to be executed end The loop is executed once for each element of the index matrix identified in the first line

Matlab for Engineers Check to see if the index has been exceeded Calculations You’ve run out of values in the index matrix Flow chart for a for loop

Matlab for Engineers Here’s a simple example In this case k is the index – the loop is repeated once for each value of k the index can be defined using any of the techniques we’ve learned

Matlab for Engineers Here’s a simple example In this case k is the index – the loop is repeated once for each value of k the index can be defined using any of the techniques we’ve learned

Matlab for Engineers One of the most common ways to use a loop is to define a matrix

Matlab for Engineers Hint Most computer programs do not have Matlab’s ability to handle matrices so easily, and therefore rely on loops similar to the one on the previous slide to define arrays. It would be easier to create the vector a in Matlab with the following code k=1:5 a = k.^2 which returns k = a = This is an example of vectorizing the code.

Matlab for Engineers Another use is in combination with an if statement to determine how many times something is true Each time through the loop we evaluate a single element of the scores matrix

Matlab for Engineers Summary of the for loop structure The loop starts with a for statement, and ends with the word end. The first line in the loop defines the number of times the loops will repeat, using an index number. The index of a for loop must be a variable. (The index is the number that changes each time through the loop.) Although k is often used as the symbol for the index, any variable name can be used. The use of k is a matter of style.

Matlab for Engineers Any of the techniques learned to define a matrix can be used to define the index matrix. One common approach is to use the colon operator. for index = start:inc:final If the expression is a row vector, the elements are used one at a time – once for each time through the loop.

Matlab for Engineers If the expression is a matrix (not common), each time through the loop the index will contain the next column in the matrix. This means that the index will be a column vector!! Once you’ve completed a for loop, the index is the last value used. for loops can often be avoided by vectorizing the code.

Matlab for Engineers While Loops While loops are very similar to for loops. The big difference is the way Matlab decides how many times to repeat the loop. While loops continue until some criterion is met. while criterion commands to be executed end

Matlab for Engineers Check to see if the criterion is still true Calculations The criterion is no longer true and the program exits the loop Flow Chart for a while loop

Matlab for Engineers We have to increment the counter (in this case k) every time through the loop – or the loop will never stop!!

Matlab for Engineers This loop creates the matrix a, one element at a time

Matlab for Engineers This program counts how many scores in the array are greater than 90, and displays the result in the command window

Matlab for Engineers Hint If you accidentally create a loop that just keeps running you should 1.Confirm that the computer is actually still calculating something by checking the lower left hand corner of the Matlab window for the “busy indicator” 2.Exit the calculation manually with ctrl c

Matlab for Engineers break and continue break causes the loop to terminate prematurely continue causes Matlab to skip a pass through the loop, but continue on until the criteria for ending is met both are used in conjunction with an if statement

Matlab for Engineers This program prompts the user 10 times to enter a value, and computes the natural log. If a negative value is entered, the break command causes Matlab to exit the loop

Matlab for Engineers To run this video, click anywhere on the screen. To move to the next slide, use the down arrow on your keyboard

Matlab for Engineers Notice that n had a value of 3 when the program terminated – if it had run to completion it would have had a value of 10

Matlab for Engineers The continue command is similar to break, however instead of terminating the loop, the program just skips to the next pass.

Matlab for Engineers To run this video, click anywhere on the screen. To move to the next slide, use the down arrow on your keyboard

Matlab for Engineers Notice that n had a value of 10 when the program terminated

Matlab for Engineers Improving the Efficiency of Loops In general, using a for loop (or a while loop) is less efficient in Matlab than using array operations.

Matlab for Engineers The amount of time it takes to run this code will depend on your computer, and how much else you have installed on it Here’s an example. This code creates a 40,000 element matrix of ones, then multiplies each element in the matrix by pi These two lines of code start a timer to measure the elapsed time required to run the lines of Matlab code between them

Matlab for Engineers This code accomplishes the same thing with a for loop

Matlab for Engineers Most of the time required to run the previous problem was used to create the B matrix one element at a time If we predefine the B matrix and then replace each element one at a time with the new value, the run time is significantly reduced

Matlab for Engineers An alternate syntax for timing uses the tic and toc functions

Matlab for Engineers Hint Be sure to suppress intermediate calculations when you use a loop. Printing those values to the screen will greatly increase the amount of execution time. If you are brave, repeat the example above, but delete the semicolons inside the loop just to check out this claim. Don’t forget that you can stop the execution of the program with ctrl c.

Matlab for Engineers Summary Sections of computer code can be categorized as sequences selection structures repetition structures

Matlab for Engineers Summary – Sequence Sequences are lists of instructions that are executed in order

Matlab for Engineers Summary – Selection Structure Selection structures allow the programmer to define criteria (conditional statements) which the program uses to choose execution paths

Matlab for Engineers Summary – Repetition Structures Repetition structures define loops where a sequence of instructions is repeated until some criterion is met (also defined by conditional statements).

Matlab for Engineers Summary – Relational Operators Matlab uses the standard mathematical relational operators < <= > >= == ~= Recall that = is the assignment operator, and can not be used for comparisons

Matlab for Engineers Summary – Logical Operators Matlab uses the standard logical operators &&and ||or ~not xorexclusive or

Matlab for Engineers Summary – Logical Functions The find command is unique to Matlab, and should be the primary logical function used in your programming It allows the user to specify a condition using both logical and relational operators, which is then used to identify elements of a matrix that meet the condition.

Matlab for Engineers Summary – if family The family of if structures allows the programmer to identify alternate computing paths dependent upon the results of conditional statements. if else elseif

Matlab for Engineers Summary - Loops Matlab supports both for loops while loops For loops are primarily used when the programmer knows how many times a sequence of commands should be executed. While loops are used when the commands should be executed until a condition is met. Most problems can be structured so that either for or while loops are appropriate.

Matlab for Engineers Summary break and continue These commands are used to exit a loop prematurely break causes the program to jump completely out of a loop and continue execution of the remainder of the program continue skips execution of the current pass through a loop, but allows the loop to continue until the completion criteria is met

Matlab for Engineers Summary - Vectorization Vectorization of Matlab code allows it to execute much more efficiently, and therefore more quickly. Loops in particular should be avoided in Matlab, although this is not always possible When loops are unavoidable they can be improved by defining “dummy” variables with placeholder values, such as ones or zeros. These placeholders can then be replaced in the loop resulting in significant improvements in execution time, which can be confirmed with timing experiments.

Matlab for Engineers Summary – timing functions The clock and etime functions are used to poll the computer clock, and then determine the time required to execute pieces of code The time calculated is the “elapsed” time. During this time the computer has not only been running Matlab code, but has also been executing background jobs and housekeeping functions. The tic and toc functions perform a similar task.