program design branching...
Post on 25-Jul-2018
221 Views
Preview:
TRANSCRIPT
EGR115 Introduction to Computing for Engineers
Chapter 4
Branching Statements &Program Design
from: S.J. Chapman, MATLAB Programming for Engineers, 5th Ed.© 2016 Cengage Learning
Chapter 4 Topics
Introduction: Program Design
4.1 Introduction to Top-Down Design Techniques
4.2 Use of Pseudocode
4.3 The Logical Data Type
4.4 Branches
4.5 More on Debugging MATLAB Programs
Program Design So far, we developed simple MATLAB programs that were executed one after another in a fixed order: these programs are called sequential programs. Typically, these programs read input data, process it to produce desired results, and stop. As a next step in programming, we need to look at the ways to design and control the order in which statements are executed in a program. Two broad Categories of Program Code Structures 1. Branches: program code structures that are designed to execute selected specific sections of
the code, based on specific logical conditions. (if and switch construct)
2. Loops: program code structures that are designed to repeat specific sections of the code ,
based on specific logical conditions. (while and for loops)
Logical Data Type In order to construct and control branches and loops, we need to employ logical data types (true or false) for defining the logical conditions.
Chapter 4Slide 1 of 17
Introduction: Program Design
Top-Down Program Design Top-down design is the process of starting with a large task and breaking it down into smaller, more easily understandable sub-tasks, which perform a portion of the desired task. Each sub-task may in turn be subdivided into smaller sub-tasks if necessary. Once the program is divided into small pieces, each piece can be coded and tested independently. Traditional Program Design & Development Process 1. State the problem you are trying to solve/Define required inputs and outputs 2. Design the algorithm 3. Convert algorithm into statements (compile) 4. Test Run the program MATLAB Program Design & Development Process 1. State the problem you are trying to solve/Define required inputs and outputs 2. Develop MATLAB Pseudocode 3. Convert Pseudocode => MATLAB statements 4. Test Run/Debug (on the fly) <= no need to compile
Chapter 4Slide 2 of 17
4.1 Introduction to Top-Down Design Techniques
Top-Down Design Process
Develop:Pseudocode
Convert:Pseudocode => MATLAB
MATLAB:Run/Debug
Finished!
COMPILE
Repeat these processes (Debug)
MATLAB Pseudocode A pseudocode is a conceptual algorithm to describe constructs (program structures). It is usually a hybrid mixture of MATLAB & English languages. It is structured like MATLAB (with a separate line for each distinct segment of code), but the descriptions on each line are written in English. You can just right click your computer’s desktop, create a simple text file (new => text
document) to get started (use notepad).
Next, the pseudocode is imported into MATLAB. Convert it to MATLAB script (m-file). Test run and debug in MATLAB (on the fly) using MATLAB symbolic debugger.
Chapter 4Slide 3 of 17
4.2 Use of Pseudocode
EXAMPLE 4-1 (from EXAMPLE 2-4)
Design a MATLAB program that reads an input temperature in degrees Fahrenheit, converts it to an absolute temperature in kelvin, and writes out the result. The relationship between temperature in degrees Fahrenheit (F) and temperature in kelvins (K) is:
1. Prompt the user to enter an input temperature in F.2. Read the input temperature.3. Calculate the temperature in kelvin.4. Write the result and stop.
5
K F 32.0 273.159
T T
Let’s create a simple Pseudocode
for this example
% MATLAB example_4_1.m
%
% 1. Prompt the user to enter an input temperature in degrees F
% 2. Read the input temperature
% temp_f <- input(’Enter the temp in degrees F’)
%
% 3. Calculate the temperature in degrees K
% temp_k <- (5/9)*(temp_f – 32)+273.15
%
% 4. Write the result and stop
% fprintf (??? temp_f = ??? temp_k)
%
% end
Notepad
Chapter 4Slide 4 of 17
4.2 Use of Pseudocode
EXAMPLE 4-2 (from EXAMPLE 2-5)A voltage source V = 120 V with an internal resistance RS of 50 W is applied to a load of resistance RL. Find the value of load resistance RL that will result in the maximum possible power being supplied by the source to the load. How much power will be supplied in this case? Also, plot the power supplied to the load as a function of the load resistance RL. In this exercise, we need to vary the load resistance RL and compute the power supplied to the load at each value of RL. The power supplied to the load resistance is given by:where I is the current supplied to the load. The current supplied to the load can be calculated by Ohm’s Law:
1. Create an array of possible values for the load resistance.2. Calculate the current for each value of RL.3. Calculate the power supplied to the load.4. Plot the power supplied to the load.
2
L LP I R
TOT S L
V VI
R R R
% MATLAB example_4_2.m
%
% 0. Must set the values of source voltage and internal resistance
% volts <- 120 / rs <- 50
%
% 1. Create an array of load resistances
% r1 <- from 1 to 100 with increment of 1
%
% 2. Calculate the current flow for each resistance
% amps <- volts/(rs+rl)
%
% 3. Calculate the power supplied to the load
% pl = (amps^2)*rl
%
% 4. Plot the power versus load resistance
% plot(rl,pl) with title, x&ylabels, grid
%
% end
Notepad
>> 3 < 4
ans = 1 (true)
>> 3 <= 4
ans = 1 (true)
>> 3 == 4
ans = 0 (false)
>> 3 > 4
ans = 0 (false)
>> 4 <= 4
ans = 1 (true)
>> ’A’ < ’B’
ans = 1 (true)
The Logical Data Type The logical data type is a special data that can have only two possible values (true or false).
If logical value is used in a place where a numerical value is expected, true is converted to 1
and false is converted to 0 (used as numerical values). Relational & Logical Operators Relational operators are operators that compare two numbers and produce a true or false
result. Logical operators are operators that compare one or two logical values, and produce a true or
false result. Relational Operators
Chapter 4Slide 5 of 17
4.3 The Logical Data Type
Logical data type = true or falsehttps://www.mathworks.com/help/matlab/operators-and-elementary-operations.html
>> a1 = true;
>> whos
Name Size Bytes Class Attributes
a1 1x1 1 logical
Command Window
Command Window
Logical Operators
Truth Tables for Logical Operations The general form of logic operations are: l1 op l2 op l1
Hierarchy of Operations 1. All arithmetic operators are evaluated first in the order previously described. 2. All relational operators (==, ~=, >, >=, <, <=) are evaluated, working from left to right. 3. All ~ operators are evaluated. 4. All & and && operators are evaluated, working from left to right. 5. All |, ||, and xor operators are evaluated, working from left to right.
Chapter 4Slide 6 of 17
4.3 The Logical Data Type
Logical data type = true or falsehttps://www.mathworks.com/help/matlab/operators-and-elementary-operations.html
>> example_4_3
a = 0
b = 0
c = 1
d = 0
e = 0
f = 1
g = -9
h = 1
j =
1 1
0 1
NOTES) (i) The && operator must be used with scalar operands. (j) AND between a scalar and an array operand. The nonzero values of array value6 are treated as true (1).
example_4_3.m
Chapter 4Slide 7 of 17
4.3 The Logical Data Type
EXAMPLE 4-3
Assuming that the following variables are initialized with the values shown, evaluate the result of the specified expressions:
value1 = 1
value2 = 0
value3 = 1
value4 = -10
value5 = 0
value6 = [1 2; 0 1]
(a)~value1
(b)~value3
(c)value1 | value2
(d)value1 & value2
(e)value4 & value5
(f)~(value4 & value5)
(g)value1 + value4
(h)value1 + (~value4)
(i)value3 && value6
(j)value3 & value6
% example_4_3.m
%
value1 = 1;
value2 = 0;
value3 = 1;
value4 = -10;
value5 = 0;
value6 = [1 2; 0 1];
%(a)
a = ~value1
%(b)
b = ~value3
%(c)
c = value1 | value2
%(d)
d = value1 & value2
%(e)
e = value4 & value5
%(f)
f = ~(value4 & value5)
%(g)
g = value1 + value4
%(h)
h = value1 + (~value4)
%(i)
%i = value3 && value6 <= Illegal!
%(j)
j = value3 & value6
Editor Command Window
>> example_4_1a
ans1 = 1
ans2 = 0
ans3 = 0
ans4 = 0
ans5 = 0
ans6 = 1
ans7 =
0 0
0 1
ans10 =
1 1 1
0 1 0
ans11 =
1 0
0 1
ans12 =
2 0
0 2
NOTES) (8) The && operator must be used with scalar operands. (9) Matrix dimensions must agree.
exercise_4_1a.m
Chapter 4Slide 8 of 17
4.3 The Logical Data Type
Do-It-Yourself (DIY) EXERCISE 4-1
Assuming that the following variables are initialized with the values shown, evaluate the result of the specified expressions:
a = 20; b = -2;
c = 0; d = 1;
1. a > b
2. b > d
3. a > b && c > d
4. a == b
5. a && b > c
6. ~~b
a = 2;
b =
;
c =
;
d =
;
7. ~(a > b)
8. a > c && b > c
9. c <= d
10. logical(d)
11. a * b > c
12. a * (b > c)
% exercise_4_1a.m
%
a = 20;
b = -2;
c = 0;
d = 1;
ans1 = a > b
ans2 = b > d
ans3 = a > b && c > d
ans4 = a == b
ans5 = a && b > c
ans6 = ~~b
%
clear
a = 2;
b = [1 -2; 0 10];
c = [0 1; 2 0];
d = [-2 1 2; 0 1 0];
ans7 = ~(a > b)
% ans8 = a > c && b > c <= Illegal!
% ans9 = c <= d <= Illegal!
ans10 = logical(d)
ans11 = a * b > c
ans12 = a * (b > c)
Editor Command Window _________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
>> example_4_1b
ans13 = 0
ans14 = 1
ans15 = 0
ans16 = 0
ans17 = 1
ans18 = 1
ans19 = 0
ans20 = 0
ans21 = -2
Logical Functions
exercise_4_1b.m
Chapter 4Slide 9 of 17
4.3 The Logical Data Type
Do-It-Yourself (DIY) EXERCISE 4-1 (continued)
Assuming that the following variables are initialized with the values shown, evaluate the result of the specified expressions:
a = 2; b = 3;
c = 10; d = 0;
13. a*b^2 > a*c
14. d || b > a
15. (d | b) > a
a = 20; b = -2;
c = 0; d = ’Test’;
16. isinf(a/b)
17. isinf(a/c)
18. a > b && ischar(d)
19. isempty(c)
20. (~a) & b
21. (~a) + b
% exercise_4_1b.m
%
a = 2;
b = 3;
c = 10;
d = 0;
ans13 = a > b
ans14 = b > d
ans15 = a > b && c > d
%
clear
a = 20;
b = -2;
c = 0;
d = 'Test';
ans16 = isinf(a/b)
ans17 = isinf(a/c)
ans18 = a > b && ischar(d)
ans19 = isempty(c)
ans20 = (~a) & b
ans21 = (~a) + b
Editor Command Window _________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
Branches Branches are MATLAB statements that permit us to select and execute specific sections of code (called blocks) while skipping other sections of code. There are two main construct types: (i) if construct and (ii) switch construct. The if Construct The control expressions (control_expr_1, control_expr_2,...) are logical
expressions.
If control_expr_1 is true, then the program executes the statements in Block 1, and skips to end.
Otherwise, the program checks for the status of control_expr_2. If control_expr_2 is true, then the program executes the statements in Block 2, and skips to end.
If all control expressions are zero (false), then the program executes the statements in the block associated with the else clause.
There can be any number of elseif clauses (0 or more) in an if construct, but there can be at most one else clause.
The switch Construct If the value of switch_expr is equal to case_expr_1, then the Block 1 will be executed, and the program will jump to end. Similarly, if the value of switch_expr is equal to case_expr_2, then the Block 2 will be executed, and the program will jump to end (and so forth). The code block otherwise is optional.
Chapter 4Slide 10 of 17
4.4 Branches
The if and switch Construct
The try/catch Construct
When a try/catch construct is reached, the statements in the try block will be executed. If no error occurs, the statements in the catch block will be skipped, and execution will continue. If an error occurs in the try block, the program will stop executing the statements in the try block, and immediately execute the statements in the catch block (then execution will continue).
Flowchart (Block Diagram) Microsoft Word provides standard shapes with flowchart templates (Insert => Shapes =>
Flowchart). It is often quite effective to use flowchart, in order to understand how the program flows (visualizing sequences of program execution).
Chapter 4Slide 11 of 17
4.4 Branches
The if and switch Construct
calc_roots.m
Chapter 4Slide 12 of 17
4.4 Branches
EXAMPLE 4-4
Write a program to solve for the roots of a quadratic equation, regardless of type.(NOTE) the solution of the quadratic equation of the form of:
can be given by:
2 4
2
b b acx
a
2 0ax bx c
MATLAB PSEUDOCODEif (b^2 – 4*a*c) < 0
Write msg that equation has two complex roots
elseif (b^2 – 4*a*c) == 0
Write msg that equation has two identical real roots
else (means: b^2 – 4*a*c > 0, but no need to specify that)
Write msg that equation has two distinct real roots
end
% calc_roots.m
disp ('This program solves for the roots of a quadratic ');
disp ('equation of the form A*X^2 + B*X + C = 0. ');
a = input ('Enter the coefficient A: ');
b = input ('Enter the coefficient B: ');
c = input ('Enter the coefficient C: ');
% Calculate discriminant
discriminant = b^2 - 4 * a * c;
% Solve for the roots, depending on the value of the discriminant
if discriminant > 0 % there are two real roots, so...
x1 = ( -b + sqrt(discriminant) ) / ( 2 * a );
x2 = ( -b - sqrt(discriminant) ) / ( 2 * a );
disp ('This equation has two real roots:');
fprintf ('x1 = %f\n', x1);
fprintf ('x2 = %f\n', x2);
elseif discriminant == 0 % there is one repeated root, so...
x1 = ( -b ) / ( 2 * a );
disp ('This equation has two identical real roots:');
fprintf ('x1 = x2 = %f\n', x1);
else % there are complex roots, so ...
real_part = ( -b ) / ( 2 * a );
imag_part = sqrt ( abs ( discriminant ) ) / ( 2 * a );
disp ('This equation has complex roots:');
fprintf('x1 = %f +i %f\n', real_part, imag_part );
fprintf('x1 = %f -i %f\n', real_part, imag_part );
end
Editor
funxy.m
Chapter 4Slide 13 of 17
4.4 Branches
EXAMPLE 4-5
Write a program to evaluate a function f (x, y) for any two user-specified values xand y. The function is defined as follows:
f (x, y) =
MATLAB PSEUDOCODE
Prompt the user for the value x and y
Read x and y (user keyboard inputs)
if x >= 0 & y >= 0
function <- x + y
elseif x >= 0 & y < 0
function <- x + y^2
elseif x < 0 & y >= 0
function <- x^2 + y
else
function <- x^2 + y^2
end
Write out f(x,y)
Input: x, yOutput: f (x,y)
Algorithm:1. Read the input values of x and y2. Calculate f (x, y)3. Write out f (x, y)
% Script file: funxy.m
% Prompt the user for the values x and y
x = input ('Enter the x value: ');
y = input ('Enter the y value: ');
% Calculate the function f(x,y) based upon
% the signs of x and y.
if x >= 0 && y >= 0
fun = x + y;
elseif x >= 0 && y < 0
fun = x + y^2;
elseif x < 0 && y >= 0
fun = x^2 + y;
else
fun = x^2 + y^2;
end
% Write the value of the function.
disp (['The value of the function is ' num2str(fun)]);
Editor
multiple_elseif.m nested_if.m
% multiple_elseif.m
%
grade = input('Enter the score: ');
if grade > 95
disp('The grade is A.')
elseif grade >86
disp('The grade is B.')
elseif grade >76
disp('The grade is C.')
elseif grade >66
disp('The grade is D.')
else
disp('The grade is F.')
end
Editor % nested_if.m
%
grade = input('Enter the score: ');
if grade > 95
disp('The grade is A.')
else
if grade > 86
disp('The grade is B.')
else
if grade > 76
disp('The grade is C.')
else
if grade > 66
disp('The grade is D.')
else
disp('The grade is F.')
end
end
end
end
Editor
exercise_4_2.m
% exercise_4_2.m
part_select = input('Select a, b, or c: ','s');
if part_select == 'a' %(a)
x = input('Enter the value of x: ');
if x >= 0
sqrt(x)
else
error('negative SQRT error')
end
elseif part_select == 'b' %(b)
numerator = input('Enter the value of numerator: ');
denominator = input('Enter the value of denominator: ');
if denominator >= 1.0E-300
numerator/denominator
else
error('divide by zero error')
end
elseif part_select == 'c' %(c)
miles = input('Enter the miles: ')
if miles <= 100
t_cost = 1.00 * miles
a_cost = t_cost / miles
elseif miles <= 200
t_cost = 1.00 * (100) + 0.80 * (miles - 100)
a_cost = t_cost / miles
else
t_cost = 1.00 * (100) + 0.80 * (200) + 0.70 * (miles - 300)
a_cost = t_cost / miles
end
else
error('Input a, b, or c ONLY!')
end
Editor _________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
NOTES) The script runs. However, if temperature is (for example) 110, this falls into true for both: > 37 and > 100 Hence, it causes an error!
exercise_4_3a.m
exercise_4_3b.m
% exercise_4_3a.m
%
volts = input('Enter volts: ');
if volts > 125
disp('WARNING: High voltage on line.')
if volts < 105
disp('WARNING: High voltage on line.')
else
disp('Line voltage is within tolerances.')
end
>> exercise_4_3a
Error: At least one END is
missing: the statement may
begin here.
% exercise_4_3b.m
%
temperature = input('Enter temperature: ');
if temperature > 37
disp('Human body temperature exceeded.')
elseif temperature > 100
disp('Boiling point of water exceeded.')
end
Editor
Editor
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
_________________________________________________________
Debug a MATLAB Program
MATLAB Code Analyzer The code analyzer provides an indicator in the top right of the MATLAB editor window. If the indicator is green, the analyzer did not detect code generation issues. If the indicator is red, the analyzer provides line by line error message with detailed explanations. Using the MATLAB Editor The MATLAB editor provides many useful features for effective code development and debugging. FILE: new/open/save scripts & functions, find/compare files, and print files. NAVIGATE: Go To Line . . ., Set/Clear bookmarks, and find commands/words. EDIT: insert section, function, comment line and indent code. BREAKPOINTS: Set/Clear, Enable/Disable breakpoints and control error handling. RUN: run, run and advance, run section, and run and time. Publishing You can publish your MATLAB Editor and Command Window in a single html file (and many other different publishing format style). PUBLISH => Publish
top related