500 likes | 674 Views
MATLAB 及其工程应用 MATLAB and It’s Engineering Application. 主讲教师: 胡章芳 E-Mail: huzf@cqupt.edu.cn. 补充 :. X1:inc:x2 linspace(x1,x2,N) generates N points between x1 and x2 x = linspace(10,20,5) x = 10.00 12.50 15.00 17.50 20.00
E N D
MATLAB及其工程应用MATLAB and It’s Engineering Application 主讲教师: 胡章芳 E-Mail: huzf@cqupt.edu.cn
补充: • X1:inc:x2 • linspace(x1,x2,N) generates N points between x1 and x2 • x = linspace(10,20,5) x = 10.00 12.50 15.00 17.50 20.00 • logspace(x1,x2) can be used for logarithmically equally spaced points
CHAPTER 3BranchingStatementsAnd Program Design Top-down Program Design&Relational and Logical Operators
Abstract • Sequential programs: • Branches: if, switch, try/catch • Loops: • Top-down Program Design • Relational and Logical Operators
Top-down designis the process of starting with a large task and breaking it down into smaller, more easily understandable pieces (subtasks), which perform a portion of the desired task. Each subtask may in turn be subdivided into smaller subtasks if necessary. Once the program is divided into small pieces, each piece can be coded and tested independently. We do not attempt to combine the subtasks into a complete task until each of the subtasks has been verified to work properly by itself. 3.1 Top-down designconcept
State theproblem Define inputsand outputs Decomposition Design thealgorithm Stepwiserefinement Convert algorithminto MATLABstatements Test theresulting program End Top-down Program Design process program Start
steps • 1.Clearly state the problem that you are trying to solve • 2.Define the inputs required by the program and the outputs to be produced by the program • 3.Design the algorithm that you intend to implement in the program • 4.Turn the algorithm into MATLAB statement • 5.Test the resulting MATLAB program 1/3 time 1/6 time 1/2 time
Testing • Test individual subtasks: unit testing • Add tested components one by one and test them together: build • Alpha release: • Beta release • Test for all legal input data sets: standard data sets, ground truth
Unit testing of individual subtasks Successive builds (adding subtasks to the program) Alpha release Beta release A typical testing process for a large program Start Subtasks validated separately As many times as necessary Subtasks combined into a single program As many times as necessary Worst bugs fixed As many times as necessary Minor bugs fixed Finished program
3.2 Use of Pseudocode • A hybrid mixture of MATLAB and English for defining algorithms • Independent of any programming language so it can be easily converted to any programming language
example 1 • Problem: write a program that takes the radius and height (in meters) of a cylinder tank and the amount of water (in m3) from the user and output the amount of extra space (in m3) in the tank. • Input: • radius and height • amount of water • Output: • extra space
example 1 • Design: • Get radius of the tank base from the user • Get the height of the tank from the user • Get the amount of water • Calculate the amount of extra space • Write the result • Step 4 is not clear enough, refine it: • Calculate the capacity of the tank(pi * radius^2 * h) • extra space capacity - water
example 1 • Code: r = input('Enter the radius of the tank base:'); h = input('Enter the height of the tank:'); water = input('Enter the amount of water:'); capacity = pi * r^2* h; space = capacity - water; fprintf('There is %f m3 extra space in the tank', space);
example 1 • Testing: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:10 There is 52.831853 m3 extra space in the tank • Continue testing: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:100 There is -37.168147 m3 extra space in the tank
3.3 Relational and Logical Operators3.3.1 Relational Operators • Relational operators are used to represent conditions (such as “space 0” in the water tank example) • Result of the condition is either true or false • In MATLAB: • false is represented by 0 • true is represented by 1 (non-zero)
The general form: a1 op a2 a1 and a2 are: arithmetic expressions ,variables, or strings Op: in table 3.1(==,~=,>,>=,<,<=) If the relationship between a1 and a2 expressed by the operator is true, then the operation returns a value of 1; Otherwise, the operation returns a value of 0
Scalar and array: • a=[1 0;-2,1], b=0,a>b • Two array • a=[1 0;-2,1], b=[0 2;-2 -1],a>=b • Evaluated after all arithmetic • 7+3<2+11 • (7+3)<(2+11)
3.3.2 Relational Operators ==and ~= • Don’t confuse equivalence (==) with assignment (=) • Relational operations have lower priority than arithmetic operations (use parentheses to be safe)
Be careful about roundoff errors during numeric comparisons. • Example: • a=0; • b=sin(pi) • a==b • abs(a-b)<1.0e-14 • (you can represent “x == y” as “abs(x-y) < 1.0e-14”)
3.3.3 Logical Operators • More complex conditions can be represented by combining relational operations using logic operators • l1 op l2 • Logical operators: & AND | OR xor ExclusiveOR ~ NOT
Scalar and array: • a=[1 0; 0,1], b=0,a&b • Two array • a=[1 0; 0,1], b=[1 1; 0 0],a|b
Operator Hierarchy • Processing order of operations: • 1.parenthesis (starting from the innermost) • 2.exponentials (left to right) • 3.multiplications and divisions (left to right) • 4.additions and subtractions (left to right) • 5.relational operators (left to right) • 6.~ operators • 7.& operators (left to right) • 8.| operators (left to right)
example 2 • Assume that the following variables are initialized with the values shown, and calculate the result of the specified expressions, value1=1, value2=0, value3=-10
3.3.4 Logical Functions • Table 3.4 • ischar(a) • isempty(a) • isinf(a) • isnan(a) • isnumeric(a) …… • Quiz 3.1
3.4 Branches • Branches are used to select and execute specific sections of the code while skipping other sections • Selection of different sections depend on a condition statement • We will learn: • if statement • switch statement
condition false statementgroup true statementgroup 3.4.1-1 Branches: “if” Statement if if ( condition ), statement 1 statement 2 ... end end
Example 1 • Examples: • if ( r <= 0 ), disp( [ ‘Radius must be positive’ ] );end • if ( ( grade < 0 ) | ( grade > 100 ) ), disp( [ ‘Grade must be in [0,100] range’ ] );end • if isinf( result ), disp( ‘Result is infinite’ );end
Example 2 • Water tank example: r = input('Enter the radius of the tank base (in meters):');if ( r <=0 ),error( ‘Radius must be positive' );endh = input('Enter the height of the tank (in meters):');if ( h <=0 ),error( ‘Height must be positive' );endw = input('Enter the amount of water (in m3):');if ( w <=0 ),error( ‘Amount of water must be positive' );endcapacity = pi * r^2* h;space = capacity - w;if ( space >0 ), disp( ['There is ' num2str(space) ' m3 extra space'] );else disp( 'Tank is full' );end
condition true false statementgroup 1 statement group 1 statement group 2 statementgroup 2 3.4.1-2 Branches: “if-else” Statement if if ( condition ), statement 1 statement 2 ... else statement 1 statement 2 ... end end
condition1 true false statementgroup 1 condition2 statement group 1 true false statementgroup 2 statement group 2 statement group 3 statementgroup 3 3.4.1-3 Branches: “if-elseif-else” Statement if if ( condition 1 ), statement 1 statement 2 ... elseif ( condition 2 ), statement 1 statement 2 ... else statement 1 statement 2 ... end end
Branching Example 3.2 • Example: Finding roots of the quadratic equation “ax2 + bx + c = 0” • Pseudocode: • d = b2– 4ac • if d > 0, two real roots elseif d == 0, two identical roots else two complex roots
Branching Examples % Prompt the user for the coefficients of the equation 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('x2 = %f -i %f\n', real_part, imag_part ); end
Branching Examples • Example: Assigning letter grades How can we compute the letter corresponding to a given numeric grade?
Branching Examples • Letter grade example: grade= input ('Enter the value of grade:'); if ( grade > 95 ), disp( ‘Grade is A’ ); elseif ( grade > 86 ), disp( ‘Grade is B’ ); elseif ( grade > 76 ), disp( ‘Grade is C’ ); elseif ( grade > 66 ), disp( ‘Grade is D’ ); else disp( ‘Grade is F’ ); end
Branching Examples if ( grade > 95 ), disp( ‘Grade is A’ ); else if ( grade > 86 ), disp( ‘Grade is B’ ); else if ( grade > 76 ), disp( ‘Grade is C’ ); else if ( grade > 66 ), disp( ‘Grade is D’ ); else disp( ‘Grade is F’ ); end end end end nested if statements
Example 3.3 -----Evaluating a Function of Tow Variable and and and and
statementgroup 1 statementgroup 2 3.4.4 “switch” Statement expression is a scalar or string constant switch ( expression ), case value 1, statement 1 statement 2 ... case value 2, statement 1 statement 2 ... ... end
statementgroup 1 statementgroup 2 optional statement group that is executed if none of the cases is satisfied Branches: “switch” Statement switch ( expression ), case {value set 1}, statement 1 statement 2 ... case {value set 2}, statement 1 statement 2 ... ... otherwise, statement 1 statement 2 ... end
Branching Examples • Example: Odd or even numbers • value=input('please enter the value:') • switch (value), • case {1,3,5,7,9}, • disp( 'Odd number' ); • case {2,4,6,8,10}, • disp('Even number'); • otherwise, • disp('Out of range'); • end
Try Block Catch Block Branches: “try/catch” Statement try statement 1 statement 2 ... catch statement 1 statement 2 ... end
a=[1 2 3;4 5 6]; b=[7 8 9;10 11 12]; try c=a*b catch d=a.*b end
Branching Examples • Example: % Initialize array a=[1 -3 2 5]; try %Try to display an element index=input('Enter subscript of element todisplay: '); disp( [ 'a(' int2str(index) ')=' num2str(a(index)) ] ); catch %If we get here an error occurred disp(['Illegal subscript: ' int2str(index)]); end Quiz 3.2
3.7 Summary • Top-down Program Design • Basic types of MATLAB branches (if, switch, try/catch) • Relational and Logical Operators • Additional information about plots(axis,hold subplot) • Control additional characteristics pf plots(boldface,italic,superscripts,font size,font name)
3.7.1 Summary of good programming practice • 1.round off • 2.Follow the steps of the program design process • 3.If and switch constructs
3.7.1 MATLAB summary • axis • figure • hold • if • ischar • isempty • iIsnan • isnumeric • polar • subplot • switch • try/catch • construct
Exercises • 3.1 • 3.2 • 3.3 • 3.4 • 3.5 • 3.11 • 3.12