1 / 50

主讲教师: 胡章芳 E-Mail: huzf@cqupt

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

margo
Download Presentation

主讲教师: 胡章芳 E-Mail: huzf@cqupt

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATLAB及其工程应用MATLAB and It’s Engineering Application 主讲教师: 胡章芳 E-Mail: huzf@cqupt.edu.cn

  2. 补充: • 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

  3. CHAPTER 3BranchingStatementsAnd Program Design Top-down Program Design&Relational and Logical Operators

  4. Abstract • Sequential programs: • Branches: if, switch, try/catch • Loops: • Top-down Program Design • Relational and Logical Operators

  5. 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

  6. State theproblem Define inputsand outputs Decomposition Design thealgorithm Stepwiserefinement Convert algorithminto MATLABstatements Test theresulting program End Top-down Program Design process program Start

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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

  13. 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);

  14. 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

  15. 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)

  16. 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

  17. 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)

  18. 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)

  19. 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”)

  20. 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

  21. Logical Operators

  22. 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

  23. 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)

  24. 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

  25. 3.3.4 Logical Functions • Table 3.4 • ischar(a) • isempty(a) • isinf(a) • isnan(a) • isnumeric(a) …… • Quiz 3.1

  26. 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

  27. condition false statementgroup true statementgroup 3.4.1-1 Branches: “if” Statement if if ( condition ), statement 1 statement 2 ... end end

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. Branching Examples • Example: Assigning letter grades How can we compute the letter corresponding to a given numeric grade?

  36. 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

  37. 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

  38. Example 3.3 -----Evaluating a Function of Tow Variable and and and and

  39. 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

  40. 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

  41. 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

  42. Try Block Catch Block Branches: “try/catch” Statement try statement 1 statement 2 ... catch statement 1 statement 2 ... end

  43. a=[1 2 3;4 5 6]; b=[7 8 9;10 11 12]; try c=a*b catch d=a.*b end

  44. 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

  45. 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)

  46. 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

  47. 3.7.1 MATLAB summary • axis • figure • hold • if • ischar • isempty • iIsnan • isnumeric • polar • subplot • switch • try/catch • construct

  48. Exercises • 3.1 • 3.2 • 3.3 • 3.4 • 3.5 • 3.11 • 3.12

More Related