0% found this document useful (0 votes)
13 views47 pages

Ch03 - Branching Statements and Program Design (Part 1)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views47 pages

Ch03 - Branching Statements and Program Design (Part 1)

Uploaded by

dgdzheng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

MATLAB Programming for Engineers

Ming Jiang

www.wcomms.com
Chapter 3: Branching Statements and
Program Design (Part 1)

Ming Jiang

www.wcomms.com
MATLAB Programming for Engineers
Chapter 3: Branching Statements and Program Design
(Part 1)

• Top-down design method


• Logical data types
• Branches

Ming Jiang
Top-down Design Method (1/2)

• “Programming is easy. However, knowing what to do


might be hard.”
• 1/3: Planning what to do
• 1/6: Writing the program
• 1/2: Testing and debugging the program
• Follow the recommended program design process to produce
reliable, understandable programs
• Top-down Design Method
• Starting with a large task and breaking it down into
smaller, more easily understandable pieces
• Each piece performs a portion of the overall task
• Each piece can be coded and tested independently
• Combine the subtasks into a complete task - after
each subtask has been verified to work properly

Ming Jiang www.wcomms.com 4


Top-down Design Method (2/2)

Start

Define the problem to solve

Define required inputs and outputs


Decomposition
Design the algorithm(s)
Stepwise refinement
Write MATLAB statements

Test the MATLAB program

End

Ming Jiang www.wcomms.com 5


General Testing Process

Start

Unit testing of individual subtasks


Subtasks validated separately
Successive building of subtasks As many times as needed
Subtasks combined into program
Alpha release As many times as needed
Worst bugs fixed
Beta release As many times as needed
Minor bugs fixed
Stable release

End

Ming Jiang www.wcomms.com 6


Use of Pseudo Codes

• Pseudocode is a hybrid mixture of MATLAB and English


• Structured like MATLAB
• One separate line in English for each distinct idea or
segment of codes
• The descriptions on each line are in English

• Benefits of using pseudocode:


• Flexible and easy to modify
• Very useful for developing algorithms
• Can be written and modified with any word processor

Example: Convert Temperatures


Prompt user to enter temperature in degrees Fahrenheit;
Read temperature in degrees Fahrenheit (temp_f);
temp_k in kelvins <− (5/9) * (temp_f - 32) + 273.15;
Write temperature in kelvins;

Ming Jiang www.wcomms.com 7


MATLAB Programming for Engineers
Chapter 3: Branching Statements and Program Design
(Part 1)

• Top-down design method


• Logical data types
• Branches

Ming Jiang
Relational and Logical Operators

Logical data type


• A special type of data that can have one of
only two possible values: true or false
• Produced by two types of MATLAB operators:
• Relational operators
• Logic operators

Ming Jiang www.wcomms.com 9


Relational Operators (1/4)

• Operators with two numerical or string operands that


yield either true (1) or false (0)
• Format: a1 op a2
where a1 and a2 are arithmetic expressions, variables,
or strings, and op is one of the relational operators

Ming Jiang www.wcomms.com 10


Relational Operators (2/4)

Examples

characters are
evaluated in
alphabetical order

• Note: two strings must have the same lengths for


comparison

Ming Jiang www.wcomms.com 11


Relational Operators (3/4)

Examples

>> a = [1 0; -2 1] >> d = [0 2; -2 -1]


a = d =
1 0 0 2
-2 1 -2 -1

>> b = 0; >> e = (a >= d) = ?


e =
>> c = (a > b) = ? 1 0
c = 1 1
1 0
0 1

Ming Jiang www.wcomms.com 12


Relational Operators (4/4)

Hierarchy of operations
• Relational operators are evaluated after all
arithmetic operators have been evaluated

Examples:
The following two expressions are equivalent

7 + 3 < 2 + 11
(7 + 3) < (2 + 11)

Ming Jiang www.wcomms.com 13


A Caution About the == and ~= Operators (1/3)

The equivalence operator (==)


• Returns true (1) or false (0) when the two values
being compared are equal or different

The non-equivalence operator (~=)


• Returns false (0) or true (1) when the two values
being compared are equal or different

Use of == and ~= operators


• Comparing strings: safe to use
• Comparing numeric values: caution needed due to
roundoff errors during computer calculations!

Ming Jiang www.wcomms.com 14


A Caution About the == and ~= Operators (2/3)

Example >> a = 0; >> a - b


>> b = sin(pi);
>> (a == b) = ? ans =
ans =
0 -1.2246e-16

Not equal to 1! Not equal to 0!

A small roundoff error in the calculation of sin(pi)


makes the result NOT exactly equal 0!

Then how to evaluate


"a==b"?
Ming Jiang www.wcomms.com 15
A Caution About the == and ~= Operators (3/3)

Good practice: use >> abs(a - b) < 1.0E-14


the abs function ans =
for comparison of
1
numeric values
Set a small number
as threshold

Ming Jiang www.wcomms.com 16


Logic Operators

• Operators with one or two logical


operands that yield a logical result
• Expressions:
•a1 op a2
•op a1

What does it
mean?

See Slide #19

Ming Jiang www.wcomms.com 17


Truth Table

Ming Jiang www.wcomms.com 18


Shortcut Evaluations
Example:
a / b > 10.0 -> any problem?
L1 && L2 v.s L1 & L2 what if b == 0?
• Difference 1: (b ~= 0) && (a/b > 10.0)
•&& supports shortcut evaluations (faster)
• Evaluate expression L1 and immediately return a false inf
value if L1 is false
• If L1 is false, the operator never evaluates L2
occurs!
•& always evaluates both L1 and L2 before answering
• Difference 2:
•&& works only between scalar values
•& works with either scalar or array values (as long as
the sizes of the arrays are compatible)

L1 || L2 v.s L1 | L2
• Similar differences as in the case of && and &

Ming Jiang www.wcomms.com 19


Logical Exclusive OR / Logical NOT

XOR operator
• The result of an exclusive OR operator is
true if and only if one operand is true
and the other one is false
• different -> true (1), same -> false (0)
• Both operands must always be evaluated
Example NOT operator
>> a = 10; • The NOT operator is a unary
>> b = 0; operator, having only one operand
>> x = xor(a, b) • The result of a NOT operator is
x = true (false) if its operand is
1 false (true)

Ming Jiang www.wcomms.com 20


Using Numeric Data with Logic Operators

• Real numeric data can also be used with logic operators


• Numeric data is converted to logical input values as:
• nonzero values  true Examples:
• zero value  false ~5 = 0
~0 = 1
Examples

>> a = [1 0; 0 1]; >> c = [1 1; 0 0]; >> xor(a,c)


>> b = 0; ans =
>> a & b >> a | c 0 1
ans = ans = 0 1
0 0 1 1
0 0 0 1

Ming Jiang www.wcomms.com 21


Hierarchy of Operations

The evaluation order for operators:


1. Parentheses ()
2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix
power (^)
3. Unary plus (+), unary minus (-), logical negation (~)
4. Multiplication (.*), right division (./), left division (.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)
5. Addition (+), subtraction (-)
6. Colon operator (:)
7. Less than (<), less than or equal to (<=), greater than (>), greater than
or equal to (>=), equal to (==), not equal to (~=)
8. Element-wise AND (&)
9. Element-wise OR (|)
Different from textbook
10.Short-circuit AND (&&)
11.Short-circuit OR (||) (4th edition)!

Ming Jiang www.wcomms.com 22


Hierarchy of Operations - Examples

Examples

>> ~(3-7) >= 1 >> ~((3-7) >= 1) ans = 1


ans = 0
>> (0&~1)|~0 ans = 1

>> ~0&~1 ans = 0

>> ~(1&~-3.5) ans = 1

Ming Jiang www.wcomms.com 23


Logical Functions (1/3)

Ming Jiang www.wcomms.com 24


Logical Functions (2/3)

Examples

>> isinf(1/0) ans = 1


>> isinf(1/10) ans = 0
>> isinf([1/10,4,9]) ans = 0 0 0
>> isinf([1/10,4,inf]) ans = 0 0 1
>> isnumeric(0611) ans = 1
>> isnumeric('0611') ans = 0
>> ischar('0611') ans = 1
>> isnumeric(0) ans = 1
>> isnumeric([1 2 3]) ans = 1
>> isnumeric('a','1','o','9') Error using isnumeric
Too many input arguments.

Ming Jiang www.wcomms.com 25


Logical Functions (3/3)

Examples

% Assume we have: % Find the solutions:


a = 3; >> ~(a >= b) ans = [0 0; 0 0]
b = [1 -1; 0 2]; >> ~a >= b ans = [0 1; 1 0]
c = [0 3; 0 2]; >> a & b >= c ans = [1 0; 1 1]
d = 1; >> (a & b) >= c ans = [1 0; 1 0]
>> b | c > a ans = [1 1; 0 1]
>> (b | c) > a ans = [0 0; 0 0]

% Assume we have: % Find the solutions:


a = 20; >> isinf(a/c) ans = 1
b = -2; >> a < b && ischar(d) ans = 0
c = 0; >> isempty(c) ans = 0
d = 'Test'; >> (~a) + b ans = -2
Automatic type
Ming Jiang www.wcomms.com
conversion 26
MATLAB Programming for Engineers
Chapter 3: Branching Statements and Program Design
(Part 1)

• Top-down design method


• Logical data types
• Branches

Ming Jiang
Branches

• Branches are MATLAB


statements that permit us to
select and execute specific
sections of code (called
blocks), while skipping other
sections of code
• Variations of the branches
• The if construct
• The switch construct
• The try/catch construct

Ming Jiang www.wcomms.com 28


Flowcharts

Graphical Representation of Algorithms

Start
Terminator
Read width
Process Read length

Total = width + length


Input/output

If total ~= 0 No/false
Decision
Yes/true
Connector Show total

Flow line Example


End

Ming Jiang www.wcomms.com 29


The if Statement (1/2)

Real Life
If I have free time,
(then) I will go to visit my GF.(period)

MATLAB
Conditions if logical expressions
statements
True end
Statements • Typically, the control expressions are
some combination of relational and
logic operators
• The code block is executed only
when the control expression = true

Ming Jiang www.wcomms.com 30


The if Statement (2/2)

a <= 30 MATLAB
if a <= 30
True
total = 2*a;
total = 2*a end

Ming Jiang www.wcomms.com 31


The if/else Statement (1/2)

Real Life
If I have free time,
I will go to visit my GF;
otherwise (else),
I will have to do MATLAB coursework.(period)

Conditions
MATLAB
True False
if logical expressions
Statement1 Statement2
statement block 1
else
statement block 2
end

Ming Jiang www.wcomms.com 32


The if/else Statement (2/2)

a <= 30
MATLAB
if a <= 30
True False total = 2*a;
total = 2*a total = a+10 else
total = a+10;
end

Ming Jiang www.wcomms.com 33


Nested Logic - if/if (1/2)
If I have free time,
Real Life
I will go to visit my GF;
(But/and) if she is busy with MATLAB coursework,
I have to wait and visit her later.(period)

False
Condition 1

True MATLAB
Statement 1 if logical expression 1
statement block 1
False if logical expression 2
Condition 2
Statement block 2
True end
Statement 2 end

Ming Jiang www.wcomms.com 34


Nested Logic - if/if (2/2)

False
a <= 30

True MATLAB
c = a + 10 if a <= 30
c = a + 10;
False if c <= 12
c <= 12 c = 0;
True end
c=0 end

Ming Jiang www.wcomms.com 35


Nested Logic - if/elseif (1/3)

Real Life

If I have free time,


I will go to visit my GF;
elseif I could finish MATLAB coursework early,
I will invite her to see a film;
else
I really have to get my MATLAB done.(period)

Ming Jiang www.wcomms.com 36


Nested Logic - if/elseif (2/3)

if logical expression 1
statement block 1
elseif logical expression 2
MATLAB
statement block 2
else
statement block 3
end Condition 1
False
True
Condition 2
Statement 1
True False
Statement 2 Statement 3

Ming Jiang www.wcomms.com 37


Nested Logic - if/elseif (3/3)

MATLAB

if a <= 30
c = a * 2
a <= 30 elseif c >= 20
False
True d = c
c >= 20 else
c=a*2
True False d = 0
d=c d=0 end

Ming Jiang www.wcomms.com 38


Example (1/3)

Example: Quadratic Equations

• The term b2-4ac: the discriminant of the equation


•b2-4ac > 0  two distinct real roots
•b2-4ac = 0  a single repeated root
•b2-4ac < 0  two complex roots

Question:
How to differentiate the above three cases?

Ming Jiang www.wcomms.com 39


Example (2/3)

Pseudo Code

% Pseudo code for differentiating


% the discriminant of a quadratic equation
if (b^2 - 4*a*c) < 0
Write a msg that equation has two complex roots
elseif (b^2 - 4*a*c) == 0
Write a msg that equation has two identical real roots
else
Write a msg that equation has two distinct real roots
end

Ming Jiang www.wcomms.com 40


Example (3/3)

MATLAB Code
% Pseudo code for differentiating
% the discriminant of a quadratic equation
if (b^2 - 4*a*c) < 0
disp('This equation has two complex roots.');
elseif (b^2 - 4*a*c) == 0
disp('This equation has two identical real roots.');
else
disp('This equation has two distinct real roots.');
end

• For readability, the blocks of code within an if construct are


usually indented by two spaces
• Read Section 3.4.2 "Examples Using if Constructs" of the
textbook to learn end-to-end MATLAB programming examples

Ming Jiang www.wcomms.com 41


Further Notes on if Constructs

• Can have as many elseif


statements as needed if grade > 95.0
disp('The grade is A.');
•elseif does not need
else
a matching end, while if grade > 86.0
else if does disp('The grade is B.');
else
if grade > 95.0 if grade > 76.0
disp('The grade is A.'); disp('The grade is C.');
elseif grade > 86.0 else
disp('The grade is B.'); if grade > 66.0
elseif grade > 76.0 disp('The grade is D.');
disp('The grade is C.'); else
elseif grade > 66.0 disp('The grade is F.');

=
disp('The grade is D.'); end
else end Equivalence
disp('The grade is F.'); end • Multiple elseif clauses
end end • Nested if constructs

Ming Jiang www.wcomms.com 42


The switch Construct
Supports multiple case expressions:
case {case_expr_1, …, case_expr_n}
• If switch_expr is equal
switch (switch_expr) to case_expr_x, the
case case_expr_1 corresponding code block
Statement 1
Statement 2
...
case case_expr_2
} Block 1
will be executed
• Then the program will
skip the remaining
code blocks and jump
Statement 1
Statement 2
...
otherwise
} Block 2
to the first statement
following the end of
the switch construct

Statement 1
Statement 2
...
end
} Block N • If none of the various
conditions case_expr_x is
satisfied, the code block of
otherwise will be executed
Ming Jiang www.wcomms.com 43
The switch Construct - Example

Example

switch (value)
case {1,3,5,7,9}
disp('The value is odd.');
case {2,4,6,8,10}
disp('The value is even.');
otherwise
disp('The value is out of range.');
end

Ming Jiang www.wcomms.com 44


The try/catch Construct

• Ordinarily, when a MATLAB program • If an error occurs in a


encounters an error while running, statement in the try block:
the program aborts • The program will stop
• But the try/catch construct executing the remaining
modifies this default behavior parts of the try block
• It is a construct designed to trap • Then executes the code
errors (useful for debugging) in the catch block
try • This allows the
programmer to handle

}
Statement 1
Statement 2 Block 1 errors within the
... program without causing
catch the program to stop

}
Statement 1
Statement 2 Block 2 • If no error occurs, the statements in
...
the catch block will be skipped
end

Ming Jiang www.wcomms.com 45


The try/catch Construct - Example

% Initialize an array which has 4 elements


a = [ 1 -3 2 5] Example
try
% Try to display an element
index = input('Enter subscript of element: ');
disp( ['a(' int2str(index) ') = ' num2str(a(index))] );
catch
% If we get here an error occurred
disp( ['Illegal subscript: ' int2str(index)] );
disp( ['It is your fault. Not mine. :)'] );
end

Enter subscript of element: 5


Illegal subscript: 5 Result
It is your fault. Not mine. :)
来自程序员的礼节式微笑...

Ming Jiang www.wcomms.com 46


版权说明

■ 本课程的课件
● 主要内容:本人制作
● 部分内容:参考了中山大学数据科学与计算机学院张雨浓教授
的2008年版课件
● 少量内容:参考了Kasetsart University的James Brucker博士
早期的课件
■ 下载地址:
http://www.wcomms.com/lectures/course-matlab.html

本课件及相关作业,仅限本课程教学使用
请勿上传互联网
谢谢合作!
WWW.WCOMMS.COM

You might also like