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

Preview:

Citation preview

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

Top-down Program Design & Relational and Logical Operators

CHAPTER 3BranchingStatements

And Program Design

Abstract

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

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.

Top-down Program Design process program

StartState theproblem

Define inputsand outputs

Design thealgorithm

Convert algorithminto MATLABstatements

Test theresulting program

End

Decomposition

Stepwiserefinement

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

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 fixedFinished program

As many times as necessary

As many times as necessary

As many times as necessary

Subtasks validated separately

Subtasks combined into a single program

Worst bugs fixed

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:

1. Get radius of the tank base from the user2. Get the height of the tank from the user3. Get the amount of water4. Calculate the amount of extra space5. 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

Operation Result

3 < 4 1

3 <= 4 1

3 == 4 0

3 ~= 4 1

3 > 4 0

4 >= 4 1

‘A’ < ‘B’ 1

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

e-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| ORxor Exclusive OR~ NOT

Logical Operators

input and or xor not

a b a & b a | b xor(a,b) ~a

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

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 valu

es 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

3.4.1-1 Branches: “if” Statement

if ( condition ),statement 1

statement 2

...

end

condition

statementgroup

true

false

statement

group

if

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

3.4.1-2 Branches: “if-else” Statement

if ( condition ),statement 1statement 2...

elsestatement 1statement 2...

end

condition

statementgroup 1

true false

statementgroup 2

statement

group 1

statement

group 2

if

end

3.4.1-3 Branches: “if-elseif-else” Statement

if ( condition 1 ),statement 1statement 2...

elseif ( condition 2 ),statement 1statement 2...

elsestatement 1statement 2...

end

statement

group 1

condition1

statementgroup 1

true false

condition2

statementgroup 2

statementgroup 3

true

false stateme

ntgroup 2

statement

group 3

if

end

Branching Example 3.2 Example: Finding roots of the quadratic eq

uation “ax2 + bx + c = 0” Pseudocode:

d = b2 – 4ac if d > 0,

two real rootselseif d == 0, two identical rootselse 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 discriminantdiscriminant = 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 ro

ot, so... x1 = ( -b ) / ( 2 * a ); disp ('This equation has two identical real root

s:'); 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?

Range Grade

100 grade > 95 A

95 grade > 86 B

86 grade > 76 C

76 grade > 66 D

66 grade > 0 F

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 Examplesif ( 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 endend

nested if statements

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

22

2

2

),(

yx

yx

yx

yx

yxf

0

0

0

0

x

x

x

x

0

0

0

0

y

y

y

yand

and

and

and

3.4.4 “switch” Statementswitch ( 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

Branches: “switch” Statementswitch ( 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

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

Branches: “try/catch” Statementtry statement 1 statement 2 ...catch statement 1 statement 2 ...end

Try Block

Catch Block

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 arraya=[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 s

ubplot) Control additional characteristics pf plots(bold

face,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

Recommended