Armstrong State University Engineering Studies MATLAB Marina Switch-Case Statements Primer

Similar documents
Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer

Armstrong Atlantic State University Engineering Studies MATLAB Marina Sorting Primer

Armstrong State University Engineering Studies MATLAB Marina Algorithm Development I Primer

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Chapter 4: Programming with MATLAB

DECISION CONTROL AND LOOPING STATEMENTS

Armstrong Atlantic State University Engineering Studies MATLAB Marina 2D Plotting Primer

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

View a Students Schedule Through Student Services Trigger:

PASCAL. PASCAL, like BASIC, is a computer language. However, PASCAL, unlike BASIC, is a Blocked Structured Language (BASIC is known as unstructured).

Introduction to Python

Shell Script Programs with If Then Else Statements

Using Variables to Write Pattern Rules

Relational & Logical Operators, if and switch Statements

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

Institute For Arts & Digital Sciences SHORT COURSES

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Scheduling WebEx Meetings with Microsoft Outlook

Pre-Calculus Advanced. Chapter 10 Part 2. Period 8

Objectives Reading SAS Data Sets and Creating Variables Reading a SAS Data Set Reading a SAS Data Set onboard ia.dfwlax FirstClass Economy

Service & Support. How do you create a weekly timer with WinCC flexible? WinCC flexible 2008 SP2. FAQ October Answers for industry.

Agenda: Discussion Week 7. May 11, 2009

1/22/2017. Chapter 2. Functions and Control Structures. Calling Functions. Objectives. Defining Functions (continued) Defining Functions

CHAPTER : 9 FLOW OF CONTROL

Simplified Operating Instructions T105-C / T108-C / T106-C / T17B-C DISPLAYS DAY OR DAY BLOCK PROG 00:0000 PROG PROG ALWAYS OFF

The Power of Perl. Perl. Perl. Change all gopher to World Wide Web in a single command

Introduction to Computing Lecture 05: Selection (continued)

General course information

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Managing Administrator Preferences

Cloning Enums. Cloning and Enums BIU OOP

Understanding the problem

Cisco HSI Backup and Restore Procedures

Lab Preparing for the ICND1 Exam

CS Introduction to Programming Fall 2016

Genesys Info Mart. date-time Section

ACT! Calendar to Excel

Problem Solving. Problem Solving Concept for Computer Science

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Nights & Weekend ROB & PHIL DECEMBER 12, 2008

Chapter 6 Reacting to Player Input

JavaScript I Language Basics

ARTT BUSINESS SCHOOL INTRODUCTION TO INFORMATION TECHNOLOGY

Creating a File and Folder Backup

New York University Introduction to Computer Science Midterm2 Sample Problems 2013 Andrew I. Case. Instructions:

Scheduling WebEx Meetings with Microsoft Outlook

Substitute Quick Reference (SmartFindExpress Substitute Calling System and Web Center)

10/9/2012. Comparison and Logical Operators The if Statement The if else Statement Nested if Statements The switch case. switch case Statement

Topic 5: Enumerated Types and Switch Statements

GreenThumb Garden Registration

Structures and Pointers

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

Lecture 3 MATLAB programming (1) Dr.Qi Ying

Scheduling WebEx Meetings with Microsoft Outlook

Math 144 Activity #4 Connecting the unit circle to the graphs of the trig functions

Note: The enumerations range from 0 to (number_of_elements_in_enumeration 1).

Lecture 12. Data Types and Strings

An Introduction to MATLAB

Arrays. Array Basics. Chapter 8 Spring 2017, CSUS. Chapter 8.1

Linked lists. Prof. Noah Snavely CS1114

Final Exam: Precalculus

7.2 Trigonometric Integrals

Conditional Formatting

Algoritma dan Struktur Data Leon Andretti Abdillah. 08 Control Flow Statements Selection by Using Switch and Case

AIMMS Function Reference - Date Time Related Identifiers

Calendar Excel Template User Guide

Long Distance Call. Long Distance Call 9/28/2015

Desktop Command window

Structure Array 1 / 50

Put the following equations to slope-intercept form then use 2 points to graph

Mechanical Engineering Department Second Year

Orange Coast College BUSINESS & COMPUTING DIVISION EVENING, WEEKEND & ONLINE COURSES. that fit your schedule and goals!

Remotely Test Any Networked Equipment

Enters system mode. Example The following example creates a scheduler named maintenancesched and commits the transaction:

Scheduling. Scheduling Tasks At Creation Time CHAPTER

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Objectives. Describe ways to create constants const readonly enum

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

BOSCH PRAESIDEO MESSAGE SCHEDULER

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Lexical Considerations

YEAR 8 STUDENT ASSESSMENT PLANNER SEMESTER 1, 2018 TERM 1

Lecture Outline. Rainfall Solution Attempt 1. Motivation for arrays. Introducing the Array. Motivation

JavaScript. Like PHP, JavaScript is a modern programming language that is derived from the syntax at C.

EECS402 Lecture 24. Something New (Sort Of) Intro To Function Pointers

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Schedule/BACnet Schedule

ECE 202 LAB 3 ADVANCED MATLAB

CSC-140 Assignment 6

ADVANCED ALGORITHMS TABLE OF CONTENTS

LN #2 (3 Hrs) Variables, Sequence Boolean Logic & Selection CTPS Department of CSE,Coimbatore

DATA VISUALIZATION Prepare the data for visualization Data presentation architecture (DPA) is a skill-set that seeks to identify, locate, manipulate,

Section 6.2 Graphs of the Other Trig Functions

(Type your answer in radians. Round to the nearest hundredth as needed.)

INFORMATION TECHNOLOGY SPREADSHEETS. Part 1

PIV Programming. Today s Contents: 1. Matlab Programming 2. An example of PIV in Matlab code 3. EDPIV 4. PIV plugin for ImageJ 5.

Trigonometry is concerned with the connection between the sides and angles in any right angled triangle.

CS 251 Intermediate Programming More on classes

CSC 337. JavaScript Object Notation (JSON) Rick Mercer

Transcription:

Armstrong State University Engineering Studies MATLAB Marina Switch-Case Statements Primer Prerequisites The Switch-Case Statements Primer assumes knowledge of the MATLAB IDE, MATLAB help, arithmetic operations, built in functions, scripts, variables, arrays, and logic expressions. Material on these topics is covered in the MATLAB Marina Introduction to MATLAB module, MATLAB Marina Variables module, MATLAB Marina Arrays module, and MATLAB Marina Logic Expressions module. Learning Objectives 1. Be able to use switch-case statements to selectively execute blocks of code. 2. Be able to use switch-case statements to selectively perform operations from a menu. Terms logical true, logical false, condition, menu MATLAB Functions, Keywords, and Operators switch, case,, Switch-Case Statements The switch-case statement is a conditional structure that is useful for handling multiple cases of the value of a single variable and enables a program to conditionally execute one block of statements from several choices or cases. Generally a switch-case statement is preferred over an if-else statement if there are four or more cases and if the cases are selected based on a single parameter. The switch-case statement has the general form shown in Figure 1a. switch switch expression case first case expression statements to be executed if first case true case second case expression statements to be executed if second case true : statements to be executed if all cases false Figure 1a, General Form of switch-case Statement The result of the MATLAB switch expression must be a scalar, string, or cell arrays of scalars or strings (cell arrays will be covered later in the MATLAB Marina Cell Array module). The result of the switch expression is compared to the result of each case expression until a match is 1

obtained. The block of statements in the case with the first match is executed. Only one block of statements is executed and the program goes to the statement after the of the switchcase statement after executing the block of statements. If the result of the switch expression does not match any of the cases, the statements in the block are executed. The block is optional and without an block it is possible for no statements in the switch-case blocks to be executed. Multiple cases can be handled with the same block of statements using a cell array of case expressions as shown in Figure 1b. All the cases for the block of statements are provided as a comma separated list enclosed in braces. For a case expression with a cell array result, the result of the switch expression needs to match at least one of the results of the case expression. case {case expression 1, case expression 2, } statements to be executed if any of cases in {} true Figure 1b, case Block for Multiple Cases A common use of the switch-case statement is to conditionally execute a block of statements based on a menu choice. The program of Figure 2 computes either the sine, cosine, or tangent of an angle based on a user menu choice. % read in angle and user choice or trig function angledegrees = input('enter angle in degrees: '); choice = menu('','sine','cosine','tangent'); % compute selected trigonometric function case {1} result = sind(angledegrees); case {2} result = cosd(angledegrees); case {3} result = tand(angledegrees); disp(result) Figure 2, Program to Compute Sine, Cosine, or Tangent Based on Menu Choice The menu function will return an integer corresponding to the number of the button selected. The variable choice will be assigned the value corresponding to the menu button pressed. In the example of Figure 2, the switch-case statement does not contain an block as the only options of the menu are the three cases. 2

The program of Figure 3a indicates whether a day of the week is a week day or week day. The day of the week is read in from the user as a string. Monday through Friday are assumed to be week days and Saturday and Sunday are assumed to be week days. Figure 3b shows an alternative implementation with all of the week day cases combined and all of the week cases combined. % read in day of week dayofweek = input('enter day of week: ', 's'); % determine if day is week day or week day switch (dayofweek) case {'sunday', 'Sunday'} disp('week day') case {'monday', 'Monday'} case {'tuesday', 'Tuesday'} case {'wednesday', 'Wednesday'} case {'thursday', 'Thursday'} case {'friday', 'Friday'} case {'saturday', 'Saturday'} disp('week ') disp('invalid day of week'); Figure 3a, Week Day or Week Day Program Generally switch-case statements should only be used when selecting a case based on an integer, a character, or a string. They should not be used when selecting a case based on a real number result as real numbers are rarely equal and matches for the cases may not occur. The case expression cannot include relational operators (result will be a Boolean which is not a legal result for a case expression). Comparisons based on relational operators should be performed using if-else statements. Only one case of a switch-case statement should evaluate to true. Only one condition of an if-else statement should evaluate to true also. It is ok for no switch-case cases to be matched or no if-else conditions to be true. Be careful when defining new variables within conditional blocks (case,, if, elseif, else blocks). If the block defining the variable is not executed, that variable will not be available later in the program unless it was previously defined. 3

% define week days and week days weekdays = {'monday', 'Monday', 'tuesday', 'Tuesday',... 'wednesday', 'Wednesday', 'thursday', 'Thursday',... 'friday', 'Friday'}; weekdays = {'sunday', 'Sunday', 'saturday', 'Saturday'}; % read in day of week dayofweek = input('enter day of week: ', 's'); % determine if day is week day or week day switch (dayofweek) case weekdays case weekdays disp('week day') disp('invalid day of week'); Figure 3b, Week Day or Week Day Program The program of Figure 4a has a potential runtime error. When the user chooses quit from the menu, the variable f will not be created (t will exist since it is created before the switchcase statement). When the plot function is encountered after a quit choice, a runtime error (Undefined function or variable 'f') occurs since the variable f was never defined. % read in plot type from user choice = menu('','sine', 'cosine', 'quit'); % generate time and trig function vectors t = (0.0 : 0.05 : 1.0); case 1 % sine f = sin(2*pi*t); case 2 % cosine f = cos(2*pi*t); disp('quit'); figure(1); plot(t,f); Figure 4a, Program to Create Sine or Cosine Plot 4

The program of Figure 4b is a corrected version of the program of Figure 4a. A Boolean variable shouldplot is initialized to true before the switch-case statement and if the quit option is selected the shouldplot flag is set to false. The figure and plot statements are executed only if shouldplot is true thus avoiding the plot statement when the variable f is not defined. % read in plot type from user choice = menu('','sine', 'cosine', 'quit'); % generate time and trig function vectors t = (0.0 : 0.05 : 1.0); shouldplot = true; case 1 % sine f = sin(2*pi*t); case 2 % cosine f = cos(2*pi*t); shouldplot = false; disp('quit'); if (shouldplot) figure(1); plot(t,f); Figure 4b, Program to Create Sine or Cosine Plot Variables should generally be defined outside of conditional structures such as switch-case and if-else blocks although they may be modified inside a block of a conditional structure. Last modified Tuesday, September 09, 2014 This work by Thomas Murphy is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. 5