Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳

Similar presentations


Presentation on theme: "MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳"— Presentation transcript:

1

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

3 补充 : 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

4 Top-down Program Design & Relational and Logical Operators CHAPTER 3 Branching Statements And Program Design

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

6 3.1 Top-down design concept Top-down design is 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.

7 Top-down Program Design process program Start State the problem Define inputs and outputs Design the algorithm Convert algorithm into MATLAB statements Test the resulting program End Decomposition Stepwise refinement

8 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

9 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

10 A typical testing process for a large program Start Unit testing of individual subtasks Successive builds (adding subtasks to the program) Alpha release Beta release Minor bugs fixed Finished program As many times as necessary Subtasks validated separately Subtasks combined into a single program Worst bugs fixed

11 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

12 example 1 Problem: write a program that takes the radius and height (in meters) of a cylinder tank and the amount of water (in m 3 ) from the user and output the amount of extra space (in m 3 ) in the tank. Input: radius and height amount of water Output: extra space

13 example 1 Design: 1. Get radius of the tank base from the user 2. Get the height of the tank from the user 3. Get the amount of water 4. Calculate the amount of extra space 5. 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

14 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);

15 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

16 3.3 Relational and Logical Operators 3.3.1 Relational Operators Relational operators are used to represent conditions (such as “ space  0 ” in the water tank example)example Result of the condition is either true or false In MATLAB: false is represented by 0 true is represented by 1 (non-zero)

17 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

18 OperationResult 3 < 41 3 <= 41 3 == 40 3 ~= 41 3 > 40 4 >= 41 ‘ A ’ < ‘ B ’ 1

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

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

21 Be careful about round off 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”)

22 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 xorExclusive OR ~NOT

23 Logical Operators inputandorxornot aba & ba | bxor(a,b)~a 000001 010111 100110 111100

24 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

25 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)

26 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

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

28 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

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

30 Example 1 Examples: if ( r <= 0 ), disp( [ ‘ Radius must be positive ’ ] ); end if ( ( grade 100 ) ), disp( [ ‘ Grade must be in [0,100] range ’ ] ); end if isinf( result ), disp( ‘ Result is infinite ’ ); end

31 Example 2 Water tank example: r = input('Enter the radius of the tank base (in meters):'); if ( r 0 ), disp( [ 'There is ' num2str(space) ' m3 extra space' ] ); else disp( 'Tank is full' ); end

32 3.4.1-2 Branches: “ if-else ” Statement if ( condition ), statement 1 statement 2... else statement 1 statement 2... end condition statement group 1 truefalse statement group 2 statement group 1 statement group 2 if end

33 3.4.1-3 Branches: “ if-elseif-else ” Statement if ( condition 1 ), statement 1 statement 2... elseif ( condition 2 ), statement 1 statement 2... else statement 1 statement 2... end statement group 1 condition 1 statement group 1 truefalse condition 2 statement group 2 statement group 3 truefalse statement group 2 statement group 3 if end

34 Branching Example 3.2 Example: Finding roots of the quadratic equation “ ax 2 + bx + c = 0 ” Pseudocode: d = b 2 – 4ac if d > 0, two real roots elseif d == 0, two identical roots else two complex roots

35 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

36 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

37 Branching Examples Example: Assigning letter grades How can we compute the letter corresponding to a given numeric grade? RangeGrade 100  grade > 95 A 95  grade > 86 B 86  grade > 76 C 76  grade > 66 D 66  grade > 0 F

38 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

39 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 nested if statements

40 Example 3.3 ----- Evaluating a Function of Tow Variable and

41 3.4.4 “ switch ” Statement switch ( expression ), case value 1, statement 1 statement 2... case value 2, statement 1 statement 2... end statement group 1 statement group 2  expression is a scalar or string constant

42 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 statement group 1 statement group 2 optional statement group that is executed if none of the cases is satisfied

43 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

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

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

46 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

47 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)

48 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

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

50 Exercises 3.1 3.2 3.3 3.4 3.5 3.11 3.12

51


Download ppt "MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳"

Similar presentations


Ads by Google