Download Control Flow Statements - Computing for Engineers - Slides | CS 1371 and more Lab Reports Computer Science in PDF only on Docsity!
1
CS
Introduction to Computing
for Engineers
Control Statements
9/4/
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
Radius R Area Circumference
INPUT CALCULATE OUTPUT
Step 3: Define test cases R=0 → Area=0 and Circumference= R=1 → Area=π and Circumference=2 π
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?
R, AREA, CIRCOUTPUT
STOP
NO YES
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> % computations; end
if condition
statements
true
false
if A> % computations; else % computations; end
if condition
statements (1)
true false statements (2)
IF-ELSEIF statement
- Can have several elseif conditions…
- else is optional and executes if all other tests fail
if A> % computations; elseif A< % 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= Interpret the following in words K> K*0 ~= 6 What if K is an array? K=ones(5,5) All elements in K are tested if K> will fail, but K(2,3)=20; if K> will also fail because ALL elements must be >10.
IF Statement and Logical Operators …cont’d
Logical Operators
OP Symbol not ~ and & or | xor xor(A,B)
Note: 0 is false Any other numeric value is true
1 1 0 1 1 0
1 0 0 1 0 1
0 1 1 1 0 1
0 0 1 0 0 0
A B ~A A|B A&B A xor B
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
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=4eye(3); try z=xy % 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
• COMMAND FUNCTION
- format short default
- format long 14 decimals
- format short e 4 decimals
- format long e 15 decimals
- format bank 2 decimals
- format + +,-,blank
M = [55.3 -22 12; 10 23.4324 30.42]
Enter the following Matrix into Matlab…
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…
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)
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’)
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