Transcript No Slide Title
Control Statements in Matlab
Learning Objectives
How is program control implemented in Matlab.?
What are the simple output statements?
Are there any special values?
• • • • • • •
Topics
IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement Display Format Special Values Summary
AE6382 Design Computing
1
Fall 2006
for loop
for j=1:10 done computations for j=1:10 % computations; end • Repeats for specified number of times • ALWAYS executes computation loop at least once!!!
• Can use + or – increments • Can escape ( BREAK ) out of computational loop
AE6382 Design Computing
2
Fall 2006
while loop
initialize k while k<10 done computations change k k=0; while k<10 % computations; k=k+1; end • 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!!!
AE6382 Design Computing
3
Fall 2006
if statements
if condition true statements false if condition true statements (1) false statements (2) if A>10 % computations; end if A>10 % computations; else % computations; end • 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!
AE6382 Design Computing
4
Fall 2006
if-elseif statement
if condition true statements (1) false elseif condition true statements (2) false
…
if A>10 % computations; elseif A<10 % computations; else % computations end elseif condition false else statements (n) statements (n+1) • Can have several elseif conditions… • Else is optional and executes if all other tests fail
AE6382 Design Computing
5
Fall 2006
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.
AE6382 Design Computing
6
Fall 2006
if Statement and Logical Operators (Cont.)
Logical Operators OP not and or xor Symbol ~ & | Note : 0 is false Anything else is true
A 0 0 1 1
AE6382 Design Computing
B 0 1 0 1 ~A 1 1 0 0 A|B 0 1 1 1 7 A&B 0 0 0 1 A xor B 0 1 1 0
Fall 2006
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)
AE6382 Design Computing
8
Fall 2006
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.
AE6382 Design Computing
9
Fall 2006
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.
AE6382 Design Computing
10
Fall 2006
More Examples
a=6; b=10; c=-2;
• Try the following examples without the use of Matlab: –
X1 = abs(c)>3 & c<(b-a) & b+a > 3
–
X2 = (b==10) | (a< 4)
–
X3 = a.*5 >= b.*3 & c < a
AE6382 Design Computing
11
Fall 2006
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 (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) 7. logical AND (&) 8. logical OR ( | )
AE6382 Design Computing
12
Fall 2006
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<40 | c>10 Three = d.*c > a.*b Four = b.*3<= 100 & d<10 & a.*d==b
AE6382 Design Computing
13
Fall 2006
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;
AE6382 Design Computing
14
Fall 2006
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;
AE6382 Design Computing
15
What’s an alternative to the if statement?
Fall 2006
Switch-Case Statement
switch case
expression 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?
AE6382 Design Computing
16
Fall 2006
Switch-case statement example
x=2.5; units=‘m’; switch case units %convert to centimeters {‘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
AE6382 Design Computing
17
Fall 2006
Display Formats
Enter the following Matrix into Matlab… M = [55.3 -22 12; 10 23.4324 30.42]
Let’s explore each format: COMMAND format short format long format short e format long e format bank format + FUNCTION default 14 decimals 4 decimals 15 decimals 2 decimals +,-,blank
AE6382 Design Computing
18
Fall 2006
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 carriage return, tab, backspace, and formfeed characters respectively.
\n,\r,\t,\b,\f can be used to produce linefeed,
• Let’s use DEMO to explore these differences.
• We will discuss I/O in further depth in a later lecture
AE6382 Design Computing
19
Fall 2006
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 end fprintf('\n Number of circles that do not have area > 20: %.0f \n', N)
AE6382 Design Computing
20
Fall 2006
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?
AE6382 Design Computing
21
Fall 2006
Special Values
These objects have special meanings in Matlab: pi i,j the value 3.1416 (How would I see more values?) sqrt(-1) (How is this represented?) inf NaN infinity (How can you prove this represents infinity?) “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
AE6382 Design Computing
22
Fall 2006
Summary
• • • • • • •
Topics
IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement Display Format Special Values Summary
Action Items
•
Review the lecture
•
Work out the simple control statement examples
•
How do these compare to other languages you have used?
AE6382 Design Computing
23
Fall 2006
Problem Statements
Sequential computation 1 Draw 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 2 Draw 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.
AE6382 Design Computing
24
Fall 2006
Problem Statements … contd.
Introduce ‘for’ loop 3 Draw a flowchart and write the MatLab code that • • • •
will calculate the area and the circumference of TEN allow the radius to be an input variable circles output radius, area and circumference IF than 20 square units.
output the number of circles with area
the area is greater 20.
Introduce ‘while’ loop 4 Draw 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 than 20 square units.
output the number of circles with area
the area is greater 20.
AE6382 Design Computing
25
Fall 2006