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

Similar documents
SMS 3515: Scientific Computing. Sem /2015

Dr. Khaled Al-Qawasmi

Lecture 15 MATLAB II: Conditional Statements and Arrays

Selection Statements

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

Relational & Logical Operators, Selection Statements

Branches, Conditional Statements

Chapter 7: Programming in MATLAB

Programming in MATLAB

Step by step set of instructions to accomplish a task or solve a problem

Selection Statements

MATLAB Operators, control flow and scripting. Edited by Péter Vass

Chapter 3: Programming with MATLAB

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

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

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Relational and Logical Operators. MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs. Examples. Logical Operators.

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

Loop Statements and Vectorizing Code

Chapter 4: Programming with MATLAB

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Matlab Programming Introduction 1 2

7 Control Structures, Logical Statements

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

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Programming in MATLAB

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Intro Chapter 1 Demo Help Lookfor Doc Quit exit Variable variablename = expression = assignment operator, initializing Incrementing Identifier names

In this lab, you will learn more about selection statements. You will get familiar to

Programming in MATLAB

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

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.

Functions of Two Variables

Introduction to programming in MATLAB

CONDITIONAL STATEMENTS AND FLOW CONTROL

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

CS 115 Lecture 8. Selection: the if statement. Neil Moore

(Refer Slide Time: 01:12)

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

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

Chapter 3: Program Statements

ECE 202 LAB 3 ADVANCED MATLAB

Case by Case. Chapter 3

A control expression must evaluate to a value that can be interpreted as true or false.

FONDAMENTI DI INFORMATICA. Prof. Emiliano Casalicchio

Desktop Command window

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

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

String Manipulation. Chapter 7. Attaway MATLAB 4E

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Mini-Matlab Lesson 5: Functions and Loops

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

CS227-Scientific Computing. Lecture 3-MATLAB Programming

User Defined Functions

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Programming for Experimental Research. Flow Control

Documentation for LISP in BASIC

Conditionals and Loops

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

Digital Image Analysis and Processing CPE

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Control Structures: if and while A C S L E C T U R E 4

An Introductory Tutorial on Matlab

Discussion 12 The MCE (solutions)

Stokes Modelling Workshop

MATLAB SUMMARY FOR MATH2070/2970

University of Alberta

AMS 27L LAB #1 Winter 2009

VBA Handout. References, tutorials, books. Code basics. Conditional statements. Dim myvar As <Type >

The following expression causes a divide by zero error:

Lists, loops and decisions

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

GNU ccscript Scripting Guide IV

Unit E Step-by-Step: Programming with Python

Introduction to Engineering gii

Top bar items. Current folder should be shown. Command Window This has the the prompt >>

DECISION MAKING STATEMENTS

H.C. Chen 1/24/2019. Chapter 4. Branching Statements and Program Design. Programming 1: Logical Operators, Logical Functions, and the IF-block

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

Decision Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

AMTH142 Lecture 12. Programming in Scilab Files in Scilab and Maxima

3 Programming. Jalal Kawash Mandatory: Chapter 5 Section 5.5 Jalal s resources: How to movies and example programs available at:

Program Elements -- Introduction

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Control Structures in Java if-else and switch

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

egrapher Language Reference Manual

Garrett Hall CSC 173 C Programming Weeks 3-4

What is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions

Python Activity 5: Boolean Expressions and Selection Statements

Functions: Decomposition And Code Reuse

9.2 Linux Essentials Exam Objectives

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

Transcription:

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

Recall Relational Expressions The relational operators in MATLAB are: > greater than < less than >= greater than or equals <= less than or equals == equality ~= inequality The resulting type is logical 1 for true or 0 for false The logical operators are: or for scalars && and for scalars ~ not Also, xor function which returns logical true if only one of the arguments is true Copyright 2013 Elsevier Inc. All rights reserved 2

If Statement The if statement is used to determine whether or not a statement or group of statements is to be executed General form: if condition action the condition is any relational expression the action is any number of valid statements (including, possibly, just one) if the condition is true, the action is executed otherwise, it is skipped entirely Copyright 2013 Elsevier Inc. All rights reserved 3

Exchanging values of variables Useful, for example, when the value of one variable is supposed to be less than another if that is not the case, exchange their values (so, an if statement is used to determine whether this is necessary or not) A temporary variable is necessary Algorithm to exchange values of variables a and b: Assign the value of a to temp Assign the value of b to a Assign the value of temp to b Copyright 2013 Elsevier Inc. All rights reserved 4

Representing true/false concepts Note: to represent the concept of false, 0 is used. To represent the concept of true, any nonzero value can be used so expressions like 5 or x result in logical true This can lead to some common logical errors For example, the following expressions are always true (because the relational expressions on the right, 6 and N, are nonzero so they are true; therefore, it does not matter what the results of the others are): number < 5 6 letter == n N Copyright 2013 Elsevier Inc. All rights reserved 5

If-else Statements The if-else statement chooses between two actions General form: if condition else action1 action2 One and only one action is executed; which one deps on the value of the condition (action1 if it is logical true or action2 if it is false) Copyright 2013 Elsevier Inc. All rights reserved 6

If-else statements are not always necessary! Simplify this statement: Answer: if num < 0 num = 0; else num = num; if num < 0 num = 0; The point is that the else clause does not accomplish anything, so it is not necessary sometimes just an if statement is all you need! Copyright 2013 Elsevier Inc. All rights reserved 7

Nested if-else Statements To choose from more than two actions, nested if-else statements can be used (an if or if-else statement as the action of another) General form: if condition1 action1 else if condition2 action2 else if condition3 action3 % etc: there can be many of these else actionn % the nth action Copyright 2013 Elsevier Inc. All rights reserved 8

The elseif clause MATLAB also has an elseif clause which shortens the code (and cuts down on the number of s) General form: if condition1 action1 elseif condition2 action2 elseif condition3 action3 % etc: there can be many of these else actionn % the nth action Copyright 2013 Elsevier Inc. All rights reserved 9

The elseif clause is not always necessary! Simplify this statement: if val >= 4 disp('ok') elseif val < 4 disp('smaller') Answer: if val >= 4 disp('ok') else disp('smaller') The point is that if you get to the else clause, you know that the expression val >= 4 is false so, val must be less than 4 so there is no need to check that. Copyright 2013 Elsevier Inc. All rights reserved 10

The switch Statement The switch statement can frequently be used in place of a nested if statement General form: switch switch_expression case caseexp1 action1 case caseexp2 action2 case caseexp3 action3 % etc: there can be many of these otherwise actionn this can be used when comparing the switch_expression to see if it is equal to the values on the case labels (the otherwise clause handles all other possible values) Copyright 2013 Elsevier Inc. All rights reserved 11

The menu function The menu function displays a menu of push-buttons, and returns the result of the button push (1 for the first button, 2 for the second, etc. or 0 if no button is pushed) Then, a switch or nested if statement isused to perform different actions based on the menu options Copyright 2013 Elsevier Inc. All rights reserved 12

Example using menu What we want is a script that prompts the user for a value of a variable x. Then, it uses the menu function to present choices between sin(x), cos(x), and tan(x). The script will print whichever function of x the user chooses. We will do this using two methods to make the choice: if-else switch Copyright 2013 Elsevier Inc. All rights reserved 13

Solution using if-else % Prints either sin, cos, or tan of x % uses the menu function to choose x = input('enter a value for x: '); choice = menu('choose a function, 'sin','cos','tan'); if choice == 1 fprintf('sin(%.1f) is %.1f\n', x, sin(x)) elseif choice == 2 fprintf('cos(%.1f) is %.1f\n', x, cos(x)) elseif choice == 3 fprintf('tan(%.1f) is %.1f\n', x, tan(x)) else disp('error!') Copyright 2013 Elsevier Inc. All rights reserved 14

Solution using switch % Prints either sin, cos, or tan of x % uses the menu function to choose x = input('enter a value for x: '); choice = menu('choose a function, 'sin','cos','tan'); switch choice case 1 fprintf('sin(%.1f) is %.1f\n', x, sin(x)) case 2 fprintf('cos(%.1f) is %.1f\n', x, cos(x)) case 3 fprintf('tan(%.1f) is %.1f\n', x, tan(x)) otherwise disp('error!') Copyright 2013 Elsevier Inc. All rights reserved 15

The is functions There are many is functions in MATLAB that essentially ask a true/false question, and return logical 1 for true or 0 for false isletter returns 1 or 0 for every character in a string whether it is a letter of the alphabet or not isempty returns 1 if the variable argument is empty, or 0 if not iskeyword returns 1 if the string argument is a keyword, or 0 if not Copyright 2013 Elsevier Inc. All rights reserved 16

Common Pitfalls Some common pitfalls have been pointed out already; others include: Using = instead of == for equality in conditions Putting a space in the keyword elseif Not using quotes when comparing a string variable to a string, such as letter == y instead of letter == 'y' Writing conditions that are more complicated than necessary, such as if (x < 5) == 1 instead of just if (x < 5) Copyright 2013 Elsevier Inc. All rights reserved 17

Programming Style Guidelines Use indentation to show the structure of a script or function. In particular, the actions in an if statement should be indented. When the else clause isn t needed, use an if statement rather than an if-else statement When using the menu function, ensure that the program handles the situation when the user clicks on the red X on the menu box rather than pushing one of the buttons. Copyright 2013 Elsevier Inc. All rights reserved 18