1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
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.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Lecture 5 Input and Output inputfprintf © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Introduction to MATLAB
MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (3): MATLAB Environment (Chapter 1)
Presenting results to the USER in a professional manner 1. semicolon, disp(), fprintf() 2. Placeholders 3. Special characters 4. Format-modifiers Output.
CSE123 Lecture 3 Different types of Variables Logical operators, Conditional Statements and If Blocks.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Input, Output, and Processing
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
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.
Flow of Control Part 1: Selection
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.
1 Week 2: Variables and Assignment Statements READING: 1.4 – 1.6 EECS Introduction to Computing for the Physical Sciences.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
Introduction to Programming with RAPTOR
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Asking the USER for values to use in a software 1 Input.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
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.
Asking the USER for values to use in a software 1 Input.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Topic Review for Exam 1 0.Infrastructure: You must be able to use MATLAB, Blackboard Exams, and Blackboard submissions 1. Computer Developing algorithms.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
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.
1 Lecture 4 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
General Computer Science for Engineers CISC 106 Lecture 13 - Midterm Review James Atlas Computer and Information Sciences 10/02/2009.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
Chapter 3 Decisions Three control structures Algorithms Pseudocode Flowcharts If…then …else Nested if statements Code blocks { } multi statement blocks.
Conditional Logic in MATLAB By Bruce Raine. How to do a basic IF – END structure in MATLAB if MATLAB Commands end i.e. do the MATLAB commands if the conditional.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Topics Designing a Program Input, Processing, and Output
Control Statements in Matlab
Chapter 4 MATLAB Programming
CS1371 Introduction to Computing for Engineers
Other Kinds of Arrays Chapter 11
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB DENC 2533 ECADD LAB 9.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
MatLab – Palm Chapter 4, Part 2 The if and switch structure
Introduction to Matlab
MatLab – Palm Chapter 4, Part 2 The if and switch structure
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.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
CS 111 Introduction to Computing in Engineering and Science
Matlab Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003

2 Control Flow Statements Topics IF Statement and Logical Operators SWITCH-CASE TRY-CATCH DISP() vs FPRINTF() Statement display formats Special values Some useful Matlab built-in functions Summary Learning Objectives Learn about how to control the sequence of expressions that are evaluated in a program.

3 Problem 1: Introducing the IF Structure Step 1: Describe Problem: Write a MatLab program to: enter the radius as an input variable calculate the area and the circumference of a circle output radius, area and circumference IF the area is greater than 20 square units. Step 2: Describe input and output Radius R Area Circumference INPUT CALCULATE OUTPUT Step 3: Define test cases R=0  Area=0 and Circumference=0 R=1  Area=  and Circumference=2 

4 Problem 1 … contd. Step 4: Develop the Solution –Describe the algorithm: –Develop the process: Calculate the area Calculate the circumference If the area is big enough, –Display radius, area and circumference –otherwise, display nothing r Area =  r 2 Circumference = 2  r START INPUT R AREA =  R 2 CIRC=2  R AREA > 20 ? OUTPUT R, AREA, CIRC STOP NO YES

5 Problem 1 … contd. % calculate the area and circumference of a circle % print it out if the area is greater than 20 radius = input('please enter a radius: '); area = pi * radius^2; circumference = 2 * pi * radius; if area > 20 fprintf('\n Radius = %f units', radius); fprintf('\n Area = %f units squared', area); fprintf('\n Circumference = %f units', circumference); end Step 4: Develop the Solution (cont’d) –Write Matlab code START INPUT R AREA =  R 2 CIRC=2  R AREA > 20 ? OUTPUT R, AREA, CIRC STOP NO YES

6 Problem 1 … contd. Step 5: Test the Results >> circle please enter a radius: 0 >> circle please enter a radius: 3 Radius = units Area = units squared Circumference = units >> circle please enter a radius: -5 Radius = units Area = units squared Circumference = units >>

7 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)

8 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

9 IF Statement and Logical Operators Relational Operators <Less than <=Less than or equal to >Greater than >=Greater than or equal to ==Equality ~=Not equal Start with a value for 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 because ALL elements must be >10.

10 IF Statement and Logical Operators …cont’d Logical Operators OPSymbol not ~ and & or | xor xor(A,B) Note: 0 is false Any other numeric value is true A xor BA&BA|B~ABA

11 Switch-Case Statement If tests of a single expression must be made for many different conditions, a SWITCH-CASE statement may be a good choice Multiple conditions are contained in a cell array switch expression case condition_1 %Do Stuff #1 case {condition_2a, condition_2b,…} %Do Stuff #2 … otherwise %Do Other Stuff end

12 SWITCH-CASE Statement Example % Demo of SWITCH-CASE control statement x = input('Enter measurement in cm: '); units = input('What output units? ', 's'); switch units case {'inch','in'} y=x./2.54; fprintf('Result is: %f inches.',y) case {'feet','ft'} y=x./2.54./12; fprintf('Result is: %f feet.',y) case {'meter','m'} y=x./100; fprintf('Result is: %f meters.',y) case {'centimeter','cm'} y=x; fprintf('Result is: %f centimeters.',y) otherwise disp(['Unknown units: ' units]) y=NaN; end input( ) used to read in a string… NEW: use [ ] in disp to concatenate strings >> basicSWITCH Enter measurement in cm: 123 What output units? ft Result is: feet. >> basicSWITCH Enter measurement in cm: 123 What ouptut units? ft Result is: feet. >> basicSWITCH Enter measurement in cm: 123 What ouptut units? m Result is: meters. >>

13 TRY-CATCH Block When Matlab encounters an error, it displays an error message and control returns to the Command prompt What if you want to: –trap the error in your program so that you can… –take corrective action without stopping execution try (commands) catch (commands if error occurs in commands) end

14 TRY-CATCH Block Example Program will not terminate if matrices cannot be multiplied –instead will set product to NaN –display a message –continue execution Can have multiple TRY-CATCH blocks in a program Similar code is used in other languages for this purpose x=ones(4,2); % create two test matrices y=4*eye(3); try z=x*y % matrix multiplication catch z=NaN; disp(‘X and Y are not conformable matrices’) end z % display or use result in rest of program >> basicTRY X and Y are not conformable matrices z = NaN >>

15 Display FORMAT 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…

16 DISP() and FPRINTF() disp(X) – prints elements of an array X disp(‘hello world’) – prints the string fprintf(fid, format, A) – does the following: –1. Write A to file fid using format (omitting fid prints to screen) –2. format is a string containing output string and format instructions for each variable in A –3. 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. –4. The special formats \n,\r,\t,\b,\f can be used to produce linefeed, carriage return, tab, backspace, and formfeed characters respectively. See help fprintf and help disp for more information about these useful functions…

17 REVIEW: INPUT( ) for Getting User Input How do you prompt user for input? Myvariable = input(‘Some String’); What if you actually want the string the user enters? Myvariable = input(‘Another String’, ‘s’); Explore the use of these functions; check out help input for more details…

18 REVIEW: Special Values These objects have special meanings in Matlab: pi the value (How would show more values?) i,j sqrt(-1) inf infinity (How can you prove this represents infinity?) NaN “Not a Number” (When do you get this message?) clock matrix with date and time date Current date in string form eps “epsilon” is the smallest amount by which two floating point values can differ on the current computer ans value just computed if not assigned

19 Built-In Functions Matlab includes all of the trig functions and their inverses (you may want to explore the tan( ) and atan( ) and atan2( ) functions which can be tricky. If X is a vector, then what do these functions do? What if X is an array? max(X) min(X) mean(X) median(X) sum(X) prod(X) cumsum(X) cumprod(X) std(X)

20 Matlab Built-In Functions … cont’d round(-2.6) fix(-2.6) floor(-2.6) ceil(-2.6) sign(-2.6) rem(15,2) %Doesn’t “mod” do the same thing? floor(ceil(10.8)) log10(100) %What’s the base of “log”? abs(-5:5) round([0:0.3:2,1:0.75:4]) On Your Own: Let’s experiment with some functions and see if you can explain how the following functions operate!

21 Built-In Functions (Cont.) These functions generate random numbers. Can you figure out the differences? randn(n) rand(n) rand(m,n) rand(‘seed’,n) rand(‘seed’)

22 Summary Action Items Review the lecture Keep exploring MATLAB! Come prepared to ask questions about MATLAB Topics Covered if Statement and Logical Operators switch-case disp() vs fprintf() input() Statement Display Format Special Values Some useful Matlab Built-in Functions Summary

23 Questions?

24