Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

Operators and Statements Assignment Statements Mathematical Operators Conditional Logic if and switch statements – Ask a question (test a condition) –
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
ITEC113 Algorithms and Programming Techniques
Programming Environment S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: Control Flow.
Computer Science 1620 Loops.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Lecture 1 The Basics (Review of Familiar Topics).
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Lecture 5 Input and Output inputfprintf © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Fall 2006AE6382 Design Computing1 Relational and Logical Operators Use relational operators to test two values Work with values of true and false Compare.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 21P. 1Winter Quarter MATLAB: Structures.
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.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
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
Chapter 3: Data Types and Operators JavaScript - Introductory.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Input, Output, and Processing
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if 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.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
1. Exam Topics Difference between computers and calculators John creates a new device. It will compute the orbit of all the planets in the solar system.
C++ Programming: Basic Elements of C++.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
ITEC113 Algorithms and Programming Techniques
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
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.,
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Week 8: Decisions Bryan Burlingame 21 October 2015.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
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 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Algorithm Discovery and Design Objectives: Interpret pseudocode Write pseudocode, using the three types of operations: * sequential (steps in order written)
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
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.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
A First Book of C++ Chapter 4 Selection.
Control Statements in Matlab
CS1371 Introduction to Computing for Engineers
More Selections BIS1523 – Lecture 9.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Iteration: Beyond the Basic PERFORM
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Matlab Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement Display Format Special Values Summary Learning Objectives How is program control implemented in Matlab.? What are the simple output statements? Are there any special values?

Fall 2006AE6382 Design Computing2 for loop Repeats for specified number of times ALWAYS executes computation loop at least once!!! Can use + or – increments Can escape (BREAK) out of computational loop for j=1:10 computations done for j=1:10 % computations; end

Fall 2006AE6382 Design Computing3 while loop Will do computational loop ONLY if while condition is met Be careful to initialize while variable Can loop forever if while variable is not updated within loop!!! while k<10 computations done change k initialize k k=0; while k<10 % computations; k=k+1; end

Fall 2006AE6382 Design Computing4 if statements Can include multiple statements Statements can also include other if statements (can nest if statements inside if statements) Be careful not to overlap (crossover) if statements! if A>10 % computations; end if condition statements true false if A>10 % computations; else % computations; end if condition statements (1) true false statements (2)

Fall 2006AE6382 Design Computing5 if-elseif statement Can have several elseif conditions… Else is optional and executes if all other tests fail if A>10 % computations; elseif A<10 % computations; else % computations end if condition statements (1) true false elseif condition elseif condition statements (2)statements (n) false … true statements (n+1) false else

Fall 2006AE6382 Design Computing6 If Statement and Logical Operators Relational Operators <less than <=less than or equal to >Greater than >=greater than or equal to ==equality ~=not equal What is the value of K? K=5 Interpret the following in words K>10 K*0 ~= 6 What if K is an array? K=ones(5,5) All elements in K are tested if K>10 will fail, but K(2,3)=20; if K>10 will also fail becase ALL elements must be >10.

Fall 2006AE6382 Design Computing7 if Statement and Logical Operators (Cont.) Logical Operators OPSymbol not ~ and & or | xor Note: 0 is false Anything else is true A xor BA&BA|B~ABA

Fall 2006AE6382 Design Computing8 Relational Operators When relational operators are present: –All arithmetic operations are performed first (in their particular order) –The relational operators are evaluated after. Example 1 –(2*3) > (4+1); % solve by hand, then type this into MATLAB -The multiplication and addition are first: -6 > 5 -The relational operator is evaluated: -6 is greater than 5, so this returns 1 (true)

Fall 2006AE6382 Design Computing9 Examples a=7; b=4; c=3; ~(a==3*b) –Evaluates 3*b = 12 –Reads: is (a==12) not (from the ~) true? –Returns ans = 1 (true) a > 5 & b > 5 –Evaluates (a>5) and (b>5) separately. –One returns true, the other returns false. –Since both are not true, the expression returns false.

Fall 2006AE6382 Design Computing10 Using Logicals in Assignments True/False values can be assigned to variables. The variables will be assigned the value that returns from relational and/or logical operators. The variables will have a value of 1 or 0. Example: –X = a > 2; Then x = 1; –Y = b==5; Y will be equal to 0.

Fall 2006AE6382 Design Computing11 More Examples a=6; b=10; c=-2; Try the following examples without the use of Matlab: –X1 = abs(c)>3 & c 3 –X2 = (b==10) | (a< 4) –X3 = a.*5 >= b.*3 & c < a

Fall 2006AE6382 Design Computing12 Operator precedence 1.transpose (.'), power (.^), complex conjugate, transpose ('), matrix power (^) 2.unary plus (+), unary minus (-), logical negation (~) 3.multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) 4.addition (+), subtraction (-) 5.colon operator (:) 6.less than ( ), greater than or equal to (>=), equal to (==), not equal to (~=) 7.logical AND (&) 8.logical OR ( | )

Fall 2006AE6382 Design Computing13 Practice Evaluate the following without Matlab: –Practice without the help of Matlab because you will not be able to use Matlab in the midterm. –a = 4; b = 20; c = 12; d = 5; –One = a>4 & b==20 –Two = b 10 –Three = d.*c > a.*b –Four = b.*3<= 100 & d<10 & a.*d==b

Fall 2006AE6382 Design Computing14 More practice When comparing vectors, the operator (>, <=, ~, &, etc.) is applied element-by-element: a = [0,2,4,2]; b = [4,1,-2,3]; What is: –C = a.* b; –C = b.^2-a.*b –C = a >= b;

Fall 2006AE6382 Design Computing15 If statement example %DEMO %Header function output = DEMO(input) %put help info here! %Do stuff if input > 0 fprintf(‘Greater than 0’) elseif input < 0 fprintf(‘Less than 0’) else fprintf(‘Equals Zero’) end %Set return value if needed outvar = 1; What’s an alternative to the if statement?

Fall 2006AE6382 Design Computing16 Switch-Case Statement switch expression case condition_1 %Do Stuff #1 case {condition_2a, condition_2b,…} %Do Stuff #2 … otherwise %Do Other Stuff end How does this relate to the ‘if’ statement?

Fall 2006AE6382 Design Computing17 Switch-case statement example x=2.5; units=‘m’; switch units %convert to centimeters case {‘inch’,’in’} y=x.*2.54; case {‘feet’,’ft’} y=x.*2.54.*12; case {‘meter’,’m’} y=x./100; case {‘centimeter’,’cm’} y=x; otherwise disp([‘Unknown units: ‘ units]) y=NaN; end

Fall 2006AE6382 Design Computing18 Display Formats Let’s explore each format: COMMANDFUNCTION format short default format long 14 decimals format short e 4 decimals format long e 15 decimals format bank 2 decimals format + +,-,blank M = [ ; ] Enter the following Matrix into Matlab…

Fall 2006AE6382 Design Computing19 Disp() and fprintf() disp(X) – prints elements of an array X disp(‘hello world’) – prints the string fprintf(fid, format, A) – does the following: –Write A to file fid using format (omitting fid prints to screen) –format is a string containing output string and format instructions for each variable in A –Variables of all printable data types: Conversion specifications involve the character %, optional flags, optional width and precision fields, optional subtype specifier, and conversion characters: d, i, o, u, x, X, f, e, E, g, G, c, and s. –The special formats \n,\r,\t,\b,\f can be used to produce linefeed, carriage return, tab, backspace, and formfeed characters respectively. Let’s use DEMO to explore these differences. We will discuss I/O in further depth in a later lecture

Fall 2006AE6382 Design Computing20 Demonstration Problem % This program will calculate the % area and circumference of ten circles, % allowing the radius as an input, % but will only provide output for circles % with an area that exceeds 20. N = 0; R = 0.0; AREA = 0.0; CIRC = 0.0; for J = 1:1:10 R = input('Please enter the radius: '); AREA = pi * R^2; CIRC = 2.0 * pi * R; if AREA > 20.0 fprintf('\n Radius = %f units',R) fprintf('\n Area = %f units squared', AREA) fprintf('\n Circumference = %f units\n', CIRC) else N = N + 1; end fprintf('\n Number of circles that do not have area > 20: %.0f \n', N)

Fall 2006AE6382 Design Computing21 Getting User Input How do I prompt user for input? Myvariable = input(‘Some String’); How can I format this better for the user? Myvariable = input(‘Another String’, ‘s’); What’s the difference between the two input lines?

Fall 2006AE6382 Design Computing22 Special Values These objects have special meanings in Matlab: pi-the value (How would I see more values?) i,j-sqrt(-1) (How is this represented?) inf -infinity (How can you prove this represents infinity?) NaN-“Not a number” (When do we get this message?) clock- matrix with date and time date – Current date in string form eps – “Epsilon” the smallest amount by which two values can differ on the current computer ans – just computed value

Fall 2006AE6382 Design Computing23 Summary Action Items Review the lecture Work out the simple control statement examples How do these compare to other languages you have used? Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement Display Format Special Values Summary

Fall 2006AE6382 Design Computing24 Problem Statements Sequential computation 1Draw a flowchart and write the MatLab code that will calculate the area and the circumference of a circle allow the radius to be an input variable output radius, area and circumference. Introduce ‘if’ structure 2Draw a flowchart and write the MatLab code that will calculate the area and the circumference of a circle allow the radius to be an input variable output radius, area and circumference IF the area is greater than 20 square units.

Fall 2006AE6382 Design Computing25 Problem Statements … contd. Introduce ‘for’ loop 3Draw a flowchart and write the MatLab code that will calculate the area and the circumference of TEN circles allow the radius to be an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20. Introduce ‘while’ loop 4Draw a flowchart and write the MatLab code that will calculate the area and the circumference of ANY NUMBER of circles allow the radius to be an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20.