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

Similar documents
7 Control Structures, Logical Statements

Chapter 7: Programming in MATLAB

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

Relational and Logical Statements

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

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

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Files and File Management Scripts Logical Operations Conditional Statements

Relational and Logical Operators

Mini-Matlab Lesson 5: Functions and Loops

Functions of Two Variables

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

LECTURE 04 MAKING DECISIONS

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

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

Structure Array 1 / 50

Chapter 4: Programming with MATLAB

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.

Relational & Logical Operators

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

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

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

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Programming for Experimental Research. Flow Control

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

Boolean Logic & Branching Lab Conditional Tests

Introduction. C provides two styles of flow control:

EL2310 Scientific Programming

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

Control Structures in Java if-else and switch

Repetition Structures

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

CS227-Scientific Computing. Lecture 3-MATLAB Programming

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Branches, Conditional Statements

EL2310 Scientific Programming

Lecture 3 MATLAB programming (1) Dr.Qi Ying

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

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

3. Logical Values. Boolean Functions; the Type bool; logical and relational operators; shortcut evaluation

Decision Making -Branching. Class Incharge: S. Sasirekha

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

Control Structures in Java if-else and switch

Review of the C Programming Language for Principles of Operating Systems

Repetition Structures Chapter 9

Computational Physics - Fortran February 1997

Programming Logic and Design Sixth Edition

Programming in MATLAB

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

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

Checking Multiple Conditions

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

XQ: An XML Query Language Language Reference Manual

Conditions, logical expressions, and selection. Introduction to control structures

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

CS 1313 Spring 2000 Lecture Outline

Quiz 1: Functions and Procedures

(Not Quite) Minijava

The PCAT Programming Language Reference Manual

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Logic, loops and control flow. NENS 230 Eddy Albarran

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

3. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

Dr. Khaled Al-Qawasmi

3. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

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

Cellular Automata Language (CAL) Language Reference Manual

Quick Reference Guide

Chapter 2: Functions and Control Structures

Computer Science & Engineering 150A Problem Solving Using Computers

Review of the C Programming Language

5. Control Statements

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Einführung in die Programmierung Introduction to Programming

5. Selection: If and Switch Controls

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

MATLIP: MATLAB-Like Language for Image Processing

Introduction to C/C++ Lecture 3 - Program Flow Control

1.00 Lecture 5. Floating Point Anomalies

Chapter 3: Programming with MATLAB

Chapter 4 Branching Statements & Program Design

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

CH6: Programming in MATLAB

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Lecture 15 MATLAB II: Conditional Statements and Arrays

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

Lecture 5 Tao Wang 1

Lecture 7 Tao Wang 1

G Programming Languages - Fall 2012

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

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

Dr. Iyad Jafar. Adapted from the publisher slides

1 Overview of the standard Matlab syntax

Selections. CSE 114, Computer Science 1 Stony Brook University

ECE 202 LAB 3 ADVANCED MATLAB

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Transcription:

C/C++ Programming for Engineers: Matlab Branches and Loops John T. Bell Department of Computer Science University of Illinois, Chicago Review What is the difference between a script and a function in Matlab? A. The first line of a function file must start with the word function, followed by the name of the function and a list of input and output arguments, following a specified format. B. Script variables share scope with the main Matlab workspace, while function variables have their own local scope. C. Functions are scripts that have been pre-compiled into binary format, so that they run faster and are not available for inspection by users. D. Both A and B. E. Both A and C. 2 1

A Common Iterative Approach Initialize Problem Set initial solution % Calculate initial solution % Estimate initial error for counter = 1:limit Current solution good enough? No Max # of iterations reached? No Improve solution Yes Yes Report best results found if( abs( error ) < tol ) break; % Improve solution % Estimate error or here % Report best solution found, % # of iterations, and estimated error. 3 Branches and Loops Branches ( decision making ) and loops are two of the most important constructs in computer programming. Branches allow code to optionally execute different code ( or none at all ) deping on the values of variables and other criteria. Loops make code repeat execution, possibly millions of times per second. 4 2

Matlab if-else Construct Syntax: if( condition ) % code to execute if true else % else and false code are optional % code to execute if false % This line is required, to mark of if If the condition is a matrix, it is considered to be true if any part of it is true ( non-zero ). 5 Matlab Relational Operators Relational operators a < b a > b a <= b a >= b a == b a ~= b Result is true if and only if: a is less than b a is greater than b a is less than or equal to b a is greater than or equal to b a is equal to b a is not equal to b No spaces allowed in <=, >=, ==, or ~= WARNING: Do not confuse == with =! If a and b are matrices, then result is a matrix. 6 3

Combined Ifs Either the true or false clauses of an if may contain any other code, including other ifs. When the true clause of an if contains another if, it is termed nested. When the false clause of an if contains another if, it is termed sequential. It is not uncommon to see long strings of sequential ifs. 7 A Nested If Example if( X <= 0.0 ) if( X < 0.0 ) fprintf( Negative ); else fprintf( Zero ); else fprintf( Positive ); 8 4

Sequential Ifs in Matlab Matlab has an elseif keyword for use in sequential ifs: if( condition ) % code to execute if true elseif( condition2 ) % Any number of these, optional % code to execute if sequential condition2 is true else % else and false code are optional % code to execute if false % This is required 9 A Sequential If Example if( X < 0.0 ) fprintf( Negative ); elseif( X > 0.0 ) fprintf( Positive ); else fprintf( Zero ); 10 5

A Longer Sequential If Example if( score >= 90.0) fprintf( A ); elseif( score >= 80.0) fprintf( B ); elseif( score >= 70.0) fprintf( C ); elseif( score >= 60.0) fprintf( D ); else fprintf( F ); Note that the order of the tests is important in this example. 11 In a series of sequential ifs, How many clauses will be executed? A. Every one that is true. B. The first one that is true. C. One of the true ones, but which one may be machine and compiler depent. D. An error will occur if more than one clause is true. E. The first one if it is true, otherwise none at all. 12 6

Matlab Logical Operators Logical operator Equivalent function Description a & b a b and(a,b) or(a,b) ~a not(a) xor(a,b) Returns true if a and b are true, meaning both are true. Returns true if a or b is true, meaning either is true (or both). Negates or complements the value of a, returning true if a is false, and vice versa. Returns true if a is true or b is true but not both, i.e., if exactly one of a or b is true. Known as exclusive or or xor (the x comes from exclusive). 13 & vs. && and vs. Matlab has two forms of the logical AND and OR operators, using one or two symbols. When dealing with matrices, the single-character versions act element-by-element, producing a matrix of results. The double-character versions are only usable with scalars, and perform short-circuit evaluation, stopping as soon as the result is known. Example: if( x ~= 0 && 1.0 / x > tol ) won t divide by 0 14 7

Precedence for Logical Operators Convention Description Explanation ( ) Items within parentheses are evaluated first. ~ not (negation) is evaluated next. & and is evaluated after not. Last to be evaluated is or. left-to-right If more than one operator of equal precedence could be evaluated, evaluation occurs left to right. For example, ~ a & b evaluates as (~a) & b. Thus a & b c evaluates as (a & b) c. The expression will always be true if both and and b are true, for example. Thus, a b c evaluates as (a b) c. 15 How do you check if X is between 0 and 10? A. if( 0.0 < X < 10.0 ) B. if( 0.0 <= X <= 10.0 ) C. if( 0.0 < X && X < 10.0 ) D. if( 0.0 <= X && X <= 10.0 ) E. if( 0.0 < X X < 10.0 ) 16 8

Matlab Relational & Logical Functions Function any(x) isnan(x) isfinite(x) isinf(x) Description Returns true if x is nonzero; otherwise, returns false. Returns true if x is NaN (Not-a- Number); otherwise, returns false. Returns true if x is finite; otherwise, returns false. For example, isfinite(inf) is false, and isfinite(10) is true. Returns true if x is +Inf or -Inf; otherwise, returns false. 17 Matlab While Loop Syntax while( condition ) % code in body of loop % required Matlab does not have do-while, but does have break & continue to be explained later. condition? True body Following code False 19 9

Input Checking With a While Loop age = -1; % Initialized to guarantee loop entry while( age < 0 age > 120 ) age = input( Please enter your age: ); if( age < 0 age > 120 ) fprintf( %d is invalid. Try again.\n, age ); fprintf( Valid ages are from 0 to 120.\n ); % Continue while input is bad 20 Matlab for loops Syntax: for variable = List_of_Values % Code to execute for each value on the list. % required The loop will execute as many times as there are values on the list, with variable taking on a separate value from the list each iteration. Sample lists: 1:10, 0:0.1*pi:pi, [ 3, 5, 8, 11 ], X 21 10

Break and Continue break causes a loop to finish immediately, continuing execution with the code following the loop body. continue causes the current iteration of a loop to finish, starting the next iteration. While loops will jump to the evaluation of the loop condition. For loops will set the loop variable to the next item on the list, provided there are items left. 22 For Loop Flowchart Illustrating break and continue for var in list % code 1 if( test_c ) continue; % code 2 if( test_b ) break; % code 3 set var to next item init var to 1 st list item True items remain? code 1 test_c code 2 test_b code 3 Following code True False 23 11

Input Checking With an Infinite Loop while( true ) % Infinite loop, until good input is given age = input( Please enter your age: ); if( age >= 0 && age <= 120 ) break; % Exit loop only when good input fprintf( %d is invalid. Try again.\n, age ); fprintf( Valid ages are from 0 to 120.\n ); % Continue while input is bad 24 Matlab Loops and Arrays It is generally NOT a good idea to use loops to access Matlab array elements. Instead use the power of Matlab to operate on entire arrays ( or subsets thereof ) in one operation. If you must use a loop to build an array element-by-element, pre-size it first to speed up operations, instead of growing the array by one element each loop iteration. 25 12

Consider a case where a variable is checked against a list of choices: direction = input( Which way?, NSEW?, s ); if( direction == W ) % Go West X = X - 1; elseif ( direction == E ) % East X = X + 1; else if ( direction == N ) % North Y = Y + 1; else if( direction == S ) % South Y = Y - 1; else fprintf( Illegal Move.\n ); switch( direction ) case W % Go West X = X - 1; case E % East X = X + 1; case N % North Y = Y + 1; case S % South Y = Y - 1; otherwise fprintf( Illegal Move. \n ); 26 Matlab switch construct Syntax: switch( expression ) case caseexpr1 % code to execute if expression == caseexpr1 % Add additional cases as needed otherwise % code to execute if no case expressions match % required Case expressions must be scalars. ( or strings or cells ) No fall-through from one case to the next. 27 13

Review Which of the following C++ logic constructs is NOT available in Matlab? A. if-else construct B. for loops C. while loops D. do-while loops E. switch construct 29 14