Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

8 - Chapman MATLAB Programming for Engineers

.pdf
Скачиваний:
91
Добавлен:
12.03.2015
Размер:
1.97 Mб
Скачать

Note that = and == mean two di erent things: == compares two variables and returns ones where they are equal and zeros where they are not; on the other hand, = is used to assign the output of an operation to a variable.

Example 8.1 Avoiding division by zero

Consider the following:

 

 

 

 

 

>> x=(-3:3)/3

 

 

 

 

 

 

x =

 

 

 

 

 

 

-1.0000

-0.6667

-0.3333

0

0.3333

0.6667

1.0000

>> sin(x)./x

 

 

 

 

 

 

Warning: Divide by zero.

 

 

 

 

ans =

 

 

 

 

 

 

0.8415

0.9276

0.9816

NaN

0.9816

0.9276

0.8415

Computing the function sin(x)/x gives a warning because the fourth element in x is zero. Since sin(0)/0 is undefined, the result for that element in the result is NaN (meaning Not a Number). The following will replace the zero in x with the special number eps, which is approximately 2.2×1016, resolving the divide-by-zero problem.

>> x = x + (x==0)*eps x =

-1.0000

-0.6667

-0.3333

0.0000

0.3333

0.6667

1.0000

 

>> sin(x)./x

 

 

 

 

 

 

 

ans =

 

 

 

 

 

 

 

0.8415

0.9276

0.9816

1.0000

0.9816

0.9276

0.8415

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Logical Operators

Logical operators provide a way to combine or negate relational expressions.

Logical

Operator Description

&and

|or

not

A fourth logical operator is implemented as a function:

xor(A,B) Exclusive or: Returns ones where either A or B is True (nonzero); returns False (zero) where both A and B are False (zero) or both are True (nonzero).

157

Definitions of the logical operators, with 0 representing False and 1 representing True:

A

B

A

A | B

A&B

xor(A,B)

0

0

1

0

0

0

0

1

1

1

0

1

1

0

0

1

0

1

1

1

0

1

1

0

The precedence from highest to lowest is relational operators, followed by logical operators , &, and |. Parentheses can be used to change the precedence and should be used liberally to clarify the operations.

Examples:

>> A=1:9

 

 

 

 

 

 

 

A =

 

 

 

 

 

 

 

 

1

2

3

4

5

6

7

8

9

>> tf1

= A>4

 

 

 

 

 

 

 

tf1 =

 

 

 

 

 

 

 

 

0

0

0

0

1

1

1

1

1

>> tf2

= ~(A>4)

 

 

 

 

 

 

 

tf2 =

 

 

 

 

 

 

 

 

1

1

1

1

0

0

0

0

0

>> tf3

= (A>2)&(A<6)

 

 

 

 

 

 

tf3 =

 

 

 

 

 

 

 

 

0

0

1

1

1

0

0

0

0

>> tf4

= xor((A>2),(A<6))

 

 

 

 

 

tf4 =

 

 

 

 

 

 

 

 

1

1

0

0

0

1

1

1

1

tf1 finds where A is greater than 4.

tf2 negates tf1, finding where A is not greater than 4.

tf3 finds where A is greater than 2 and less than 6.

tf4 find where the exclusive or of (A>2) and (A<6), which is observed to be the same as the logical inverse of tf3.

Example 8.2 Generating discontinuous signals

The logical operators allow the generation of arrays representing signals with discontinuities or signals that are composed os segments of other signals. The basic idea is to multiply those values in a array that are to be retained with ones, and multiply all other values with zeros.

Consider the discontinuous signal:

x(t) =

sin(t) sin(t) > 0 0 sin(t) < 0

158

The following script computes and plots this signal over the range t = [0,10] s.

t = linspace(0,10,100);

% create x vector

x = sin(t);

%

compute sine

vector

x = x.*(x>0);

%

set negative

values of sin(t) to zero

%

 

 

 

% Plot x and label

plot(t,x),xlabel(’Time (s)’),ylabel(’Amplitude’),...

title(’Discontinuous signal’), axis([0 10 -0.1 1.1])

The plot that is generated is shown in Figure 8.1.

Discontinuous signal

1

 

 

 

 

 

 

 

 

 

 

0.8

 

 

 

 

 

 

 

 

 

 

0.6

 

 

 

 

 

 

 

 

 

 

Amplitude

 

 

 

 

 

 

 

 

 

 

0.4

 

 

 

 

 

 

 

 

 

 

0.2

 

 

 

 

 

 

 

 

 

 

0

 

 

 

 

 

 

 

 

 

 

0

1

2

3

4

5

6

7

8

9

10

 

 

 

 

 

Time (s)

 

 

 

 

 

Figure 8.1: Plot of a discontinuous signal

Relational and Logical Functions

Matlab provides several useful relational and local functions that operate on scalars, vectors, and matrices. The following is a partial list of these functions.

159

Function

Description

any(x)

Returns a scalar that is 1 (true) if any element in the vector x is

 

nonzero; otherwise, the scalar is 0 (false). Returns a row vector

 

containing a 1 (true) in each element for which any element of the

 

corresponding column of matrix x is nonzero, and a 0 (false) other-

 

wise.

all(x)

Returns a scalar that is 1 (true) if all elements in the vector x are

 

nonzero; otherwise, the scalar is 0 (false). Returns a row vector

 

containing a 1 (true) in each element for which all elements of the

 

corresponding column of matrix x are nonzero, and a 0 (false) oth-

 

erwise.

find(x)

Returns a vector containing the indices of the nonzero elements of

 

a vector x. Returns a vector containing the indices of the nonzero

 

elements of x(:), which is a single-column vector formed from the

 

columns of matrix x.

isnan(x)

Returns an array with ones where the elements of x are NaN and zeros

 

where they are not.

isfinite(x)

Returns an array with ones where the elements of x are finite and

 

zeros where they are not. For example, isfinite([pi NaN Inf

 

-Inf]) is [1 0 0 0].

isinf(x)

Returns an array with ones where the elements of x are +Inf or -Inf

 

and zeros where they are not.

isempty(x)

Returns 1 if x is an empty array and 0 otherwise.

Example 8.3 Height and speed of a projectile

The height and speed of a projectile (such as a thrown ball) launched with a speed of v0 at an angle θ to the horizontal are given by

h(t) = v0t sin θ − 0.5gt2

v(t) = v02 2v0gt sin θ + g2t2

where g is the acceleration due to gravity. The projectile will strike the ground when h(t) = 0, which gives the time to return to the ground, tg = 2(v0/g) sin θ. For θ = 40, v0 = 20 m/s, and g = 9.81 m/s2, determine the times when the height is no less than 6m and the speed is simultaneously no greater than 16 m/s.

This problem can be solved by using the find command to determine the times at which the logical expression (h >= 6 & (v <= 16) is ture.

%Set the values for initial speed, gravity, and angle v0 = 20; g = 9.81; theta = 40*pi/180;

%Compute the time to return to the ground

t_g = 2*v0*sin(theta)/g;

160

%Compute the arrays containing time, height, and speed. t = [0:t_g/200:t_g];

h = v0*t*sin(theta) - 0.5*g*t.^2;

v = sqrt(v0^2 - 2*v0*g*sin(theta)*t + g^2*t.^2);

%Determine when the height is no less than 6,

%and the speed is no greater than 16.

u = find(h>6 & v <= 16);

% Compute the corresponding times t_1 = t(u(1))

t_2 = t(u(end))

The beginning of the time interval, t1 is the value of t indexed by the first element of u and the end of the time interval, t2 is the value of t indexed by the last element of u.

The results are:

t_1 = 0.8518

t_2 = 1.7691

This problem could have been solved by plotting h(t) and v(t), but the accuracy of the results would be limited by our ability to pick points o the graph. In addition, the graphical approach is more time-consuming.

8.2Flow Control

Selection statements that test the results of relational or logical functions or operators are the decision-making structures that allow the flow of command execution to be controlled.

For more information: help lang.

Simple if Statement

The general form of a simple if statement is:

if logical expression commands

end

If the logical expression is true, the commands between the if statement and the end statement are executed. If the logical expression is false, the flow of execution jumps immediately to the end statement without executing the statements between the if statement and the end statement.

161

To help in reading and understanding an if structure, it is good style to indent the statements within the structure.

Example:

if d < 50

count = count + 1; disp(d);

end

Assuming that d is a scalar, then if d is less than 50, count is incremented by 1 and the value of d is displayed; otherwise, these two statements are skipped. If d is not a scalar, then count is incremented by 1 and d is displayed only if every element of d is less than 50.

Nested if Statements

if statements may be nested, as shown in the following example:

if d < 50

count = count + 1; disp(d);

if b > d b = 0;

end

end

Assuming first that b and d are scalars, then if d<50, count is incremented by 1 and d is displayed. In addition, if b>d, then b is set to 0. If d is not less than 50, we skip immediately to the second end statement.

else and elseif Clauses

else clause: allows one set of statements to be executed if a logical expression is true and a di erent set if the logical expression is false.

For example, if variable interval is less than one, set the value of xinc to interval/10; otherwise, set the value of xinc to 0.1.

if interval < 1

xinc = interval/10; else

xinc = 0.1;

end

162

When several levels of if-else statements are nested, it may be di cult to determine which logical expressions must be true (or false) to execute each set of statement. In these cases, the elseif clause is often used to clarify the program logic, as shown in the example below.

if temperature > 100

disp(’Too hot - equipment malfunctioning.’) elseif temperature > 90

disp(’Normal operating range.’) elseif temperature > 50

disp(’Below desired operating range.’) else

disp(’Too cold - turn off equipment.’)

end

In this example, temperature between 90 and 100 are in the normal operating range; temperatures outside this range generate an appropriate message.

Example 8.4 Testing variable type

The if command can be used to write a function M-file to take a single input argument and then report, in text, whether that argument is scalar, vector, or matrix. No argument is returned.

function testvar(x)

%Display text indicating whether x is a

%scalar, vector, or matrix

[m,n] = size(x); if m==n & m==1

disp(’

Argument is a scalar’)

elseif m==1 | n==1

disp(’

Argument is a vector’)

else

 

disp(’

Argument is a matrix’)

end

 

A test of this function:

>>a=2; b=[2 3]; c=[4 5; 6 7];

>>testvar(a)

Argument is a scalar >> testvar(b)

Argument is a vector >> testvar(c)

Argument is a matrix

163

Switch Selection Structure

The switch selection structure provides an alternative to using the if, elseif, and else commands. Anything programmed using if structures can also be programmed using switch structures. The advantage of the switch structure is that in some situations, it yields code that is more readable.

The syntax is

switch expression

case test expression 1 commands

case {test expression 2, test expression 3} commands

·

·

·

otherwise commands

end

The expression result is compared in turn to the result of each case test expression. If they are equal, then the commands following the case command are executed and processing continues with the command following the end statement. If expression is a character string, then a string comparison is made with the case test expression. Multiple test expressions can be listed, comma separated, enclosed in braces {}. Only the first matching case is executed, If no match occurs, the statements following the otherwise statement are executed. However, the otherwise statement is optional. If it is absent, execution continues with the command following the end statement if no match exists. Each case test expression statement must be on a single line.

Consider an example that was previously implemented with an if, else structure:

switch interval < 1 case 1

xinc = interval/10; case 0

xinc = 0.1;

end

For this example, the resulting code is no more readable than in the previous implementation.

An example using string comparisons:

x = 6.1; units = ’ft’;

% convert x to meters switch units

case {’inch’,’in’}

164

y = x*0.0254; case{’feet’,’ft’} y = x*0.3048; case{’meter’,’m’}

y = x; case{’centimeter’,’cm’}

y = x/100; case{’millimeter’,’mm’}

y = x/1000; otherwise

disp([’Unknown units: ’ units]) y = NaN;

end

Executing this example gives a final value of y = 1.8593.

8.3Loops

A loop is a structure that allows a group of commands to be repeated.

for Loop

A for loop repeats a group of commands a fixed, predetermined number of times. A for loop has the following structure:

for variable=expression commands

end

The commands between the for and end statements are executed once for every column in the expression, beginning with the first column and stepping through to the last column. At each step, known as an iteration, the appropriate column of the expression is assigned to the variable. Thus, on step n, column n of the expression is assigned to the variable, which then can be operated on by one of the commands in the loop.

Rules for writing and using a for loop include:

1.If the expression results in an empty matrix, the loop will not be executed. Control will pass directly to the statement following the end statement.

2.If the result of the expression is a scalar, the loop will be executed once, with the variable equal to the value of the scalar.

3.If the result of the expression is a vector, then each time through the loop, the variable will contain the next value in the vector.

165

4.A for loop cannot be terminated by reassigning the loop variable within the loop.

5.Upon completion of a for loop, the variable contains the last value used.

6.The colon operator can be used to define the expression using the following format for index = initial:increment:limit

Example 8.5 Use of a for statement in a function

Consider writing a user-defined function that searches a matrix input argument for the element with the largest value and returns the indices of that element.

function [r,c] = indmax(x)

%INDMAX returns the row and column indices of

%the maximum-valued element in x

[m n] = size(x); xmax = x(1,1); r=1; c=1;

for k=1:m for l=1:n

if x(k,l)> xmax xmax = x(k,l); r=k;

c=l;

end

end end

Testing this function:

>>A=3; B=[2 4 3]; C=[3 2; 6 1];

>>[r c]=indmax(A)

r =

1

c =

1

>>[r c]=indmax(B)

r =

1

c =

2

>>[r c]=indmax(C)

r =

2

c =

1

166

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]