Using MATLAB (779505), страница 76
Текст из файла (страница 76)
Relational operators always operateelement-by-element. In this example, the resulting matrix shows where anelement of A is equal to the corresponding element of B.A = [2 7 6;9 0 5;3 0.5 6];B = [8 7 0;3 2 5;4 –1 7];A == Bans =000100010For vectors and rectangular arrays, both operands must be the same sizeunless one is a scalar.
For the case where one operand is a scalar and the otheris not, MATLAB tests the scalar against every element of the other operand.Locations where the specified relation is true receive the value 1. Locationswhere the relation is false receive the value 0.17-28OperatorsRelational Operators and Empty ArraysThe relational operators work with arrays for which any dimension has sizezero, as long as both arrays are the same size or one is a scalar. However,expressions such asA == []return an error if A is not 0-by-0 or 1-by-1.To test for empty arrays, use the functionisempty(A)Logical OperatorsThis section describes the MATLAB logical operators and also covers:• “Using Logical Operators on Arrays”• “Logical Functions”• “Logical Expressions Using the find Function”MATLAB provides these logical operators.OperatorDescription&AND|OR~NOTNote In addition to these logical operators, the ops directory contains anumber of functions that perform bitwise logical operations.
See online helpfor more information.17-2917M-File ProgrammingEach logical operator has a specific set of rules that determines the result of alogical expression:• An expression using the AND operator, &, is true if both operands are logicallytrue. In numeric terms, the expression is true if both operands are nonzero.This example shows the logical AND of the elements in the vector u with thecorresponding elements in the vector v.u = [1 0 2 3 0 5];v = [5 6 1 0 0 7];u & vans =101001• An expression using the OR operator, |, is true if one operand is logically true,or if both operands are logically true. An OR expression is false only if bothoperands are false.
In numeric terms, the expression is false only if bothoperands are zero. This example shows the logical OR of the elements in thevector u and with the corresponding elements in the vector v.u | vans =111101• An expression using the NOT operator, ~, negates the operand.
This producesa false result if the operand is true, and true if it is false. In numeric terms,any nonzero operand becomes zero, and any zero operand becomes one. Thisexample shows the negation of the elements in the vector u.~uans =017-3010010OperatorsUsing Logical Operators on ArraysMATLAB’s logical operators compare corresponding elements of arrays withequal dimensions.
For vectors and rectangular arrays, both operands must bethe same size unless one is a scalar. For the case where one operand is a scalarand the other is not, MATLAB tests the scalar against every element of theother operand. Locations where the specified relation is true receive the value1. Locations where the relation is false receive the value 0.Logical FunctionsIn addition to the logical operators, MATLAB provides a number of logicalfunctions.FunctionDescriptionExamplesxorPerforms an exclusive OR on itsoperands. xor returns true if oneoperand is true and the other false.In numeric terms, the functionreturns 1 if one operand is nonzeroand the other operand is zero.a = 1;b = 1;xor(a,b)Returns 1 if all of the elements in avector are true or nonzero.
alloperates columnwise on matrices.A = [0 1 2;3 5 0]allans =0A =03152010all(A)ans =0anyReturns 1 if any of the elements of itsargument are true or nonzero;otherwise, it returns 0. Like all, theany function operates columnwise onmatrices.v = [5 0 8];any(v)ans =117-3117M-File ProgrammingA number of other MATLAB functions perform logical operations. For example,the isnan function returns 1 for NaNs; the isinf function returns 1 for Infs.
Seethe ops directory for a complete listing of logical functions.Logical Expressions Using the find FunctionThe find function determines the indices of array elements that meet a givenlogical condition. It’s useful for creating masks and index matrices. In its mostgeneral form, find returns a single vector of indices. This vector can be used toindex into arrays of any size or shape. For example,A = magic(4)A =16594211714310615138121i = find(A > 8);A(i) = 100A =10051004210071003100610010081001You can also use find to obtain both the row and column indices for arectangular matrix, as well as the array values that meet the logical condition.Use the help facility for more information on find.Operator PrecedenceYou can build expressions that use any combination of arithmetic, relational,and logical operators. Precedence levels determine the order in whichMATLAB evaluates an expression.
Within each precedence level, operatorshave equal precedence and are evaluated from left to right. The precedence17-32Operatorsrules for MATLAB operators are shown in this list, ordered from highestprecedence level to lowest precedence level:1 Parentheses ()2 Transpose(.'), power(.^), complex conjugate transpose(’), matrix power(^)3 Unary plus (+), unary minus (-), logical negation (~)4 Multiplication (.*), right division (./), left division(.\), matrixmultiplication (*), matrix right division (/), matrix left division (\)5 Addition (+), subtraction (-)6 Colon operator (:)7 Less than (<), less than or equal to (<=), greater than (>), greater than orequal to (>=), equal to (==), not equal to (~=)8 Logical AND (&)9 Logical OR (|)Overriding Default PrecedenceThe default precedence can be overridden using parentheses, as shown in thisexample.A = [3 9 5];B = [2 1 5];C = A./B.^2C =0.75009.00000.200081.00001.0000C = (A./B).^2C =2.250017-3317M-File ProgrammingExpressions can also include values that you access through subscripts.b = sqrt(A(2)) + 2*B(1)b =717-34Flow ControlFlow ControlThere are eight flow control statements in MATLAB:• if, together with else and elseif, executes a group of statements based onsome logical condition.• switch, together with case and otherwise, executes different groups ofstatements depending on the value of some logical condition.• while executes a group of statements an indefinite number of times, basedon some logical condition.• for executes a group of statements a fixed number of times.• continue passes control to the next iteration of a for or while loop, skippingany remaining statements in the body of the loop.• break terminates execution of a for or while loop.• try...catch changes flow control if an error is detected during execution.• return causes execution to return to the invoking function.All flow constructs use end to indicate the end of the flow control block.Note You can often speed up the execution of MATLAB code by replacing forand while loops with vectorized code.
See “Optimizing MATLAB Code” onpage 17-71.if, else, and elseifif evaluates a logical expression and executes a group of statements based onthe value of the expression. In its simplest form, its syntax isif logical_expressionstatementsendIf the logical expression is true (1), MATLAB executes all the statementsbetween the if and end lines. It resumes execution at the line following the endstatement.
If the condition is false (0), MATLAB skips all the statementsbetween the if and end lines, and resumes execution at the line following theend statement.17-3517M-File ProgrammingFor example,if rem(a,2) == 0disp('a is even')b = a/2;endYou can nest any number of if statements.If the logical expression evaluates to a nonscalar value, all the elements of theargument must be nonzero. For example, assume X is a matrix. Then thestatementif Xstatementsendis equivalent toif all(X(:))statementsendThe else and elseif statements further conditionalize the if statement:• The else statement has no logical condition.
The statements associated withit execute if the preceding if (and possibly elseif condition) is false (0).• The elseif statement has a logical condition that it evaluates if thepreceding if (and possibly elseif condition) is false (0).
The statementsassociated with it execute if its logical condition is true (1). You can havemultiple elseifs within an if block.if n < 0% If n negative, display error message.disp('Input must be positive');elseif rem(n,2) == 0 % If n positive and even, divide by 2.A = n/2;elseA = (n+1)/2;% If n positive and odd, increment and divide.end17-36Flow Controlif Statements and Empty ArraysAn if condition that reduces to an empty array represents a false condition.That is,if AS1elseS0endwill execute statement S0 when A is an empty array.switchswitch executes certain statements based on the value of a variable orexpression.
Its basic form isswitch expressioncase value1statementscase value2statements...otherwisestatements(scalar or string)% Executes if expression is value1% Executes if expression is value2% Executes if expression does not% does not match any caseendThis block consists of:• The word switch followed by an expression to evaluate.• Any number of case groups. These groups consist of the word case followedby a possible value for the expression, all on a single line.
Subsequent linescontain the statements to execute for the given value of the expression.These can be any valid MATLAB statement including another switch block.Execution of a case group ends when MATLAB encounters the next casestatement or the otherwise statement. Only the first matching case isexecuted.17-3717M-File Programming• An optional otherwise group.
This consists of the word otherwise, followedby the statements to execute if the expression’s value is not handled by anyof the preceding case groups. Execution of the otherwise group ends at theend statement.• An end statement.switch works by comparing the input expression to each case value. Fornumeric expressions, a case statement is true if (value==expression). Forstring expressions, a case statement is true if strcmp(value,expression).The code below shows a simple example of the switch statement. It checks thevariable input_num for certain values.
If input_num is –1, 0, or 1, the casestatements display the value on screen as text. If input_num is none of thesevalues, execution drops to the otherwise statement and the code displays thetext 'other value'.switch input_numcase –1disp('negative one');case 0disp('zero');case 1disp('positive one');otherwisedisp('other value');endNote For C Programmers unlike the C language switch construct,MATLAB’s switch does not “fall through.” That is, if the first case statementis true, other case statements do not execute.
Therefore, break statements arenot used.switch can handle multiple conditions in a single case statement by enclosingthe case expression in a cell array.17-38Flow Controlswitch varcase 1disp('1')case {2,3,4}disp('2 or 3 or 4')case 5disp('5')otherwisedisp('something else')endwhileThe while loop executes a statement or group of statements repeatedly as longas the controlling expression is true (1).
Its syntax iswhile expressionstatementsendIf the expression evaluates to a matrix, all its elements must be 1 for executionto continue. To reduce a matrix to a scalar value, use the all and any functions.For example, this while loop finds the first integer n for which n! (n factorial)is a 100-digit number.n = 1;while prod(1:n) < 1e100n = n + 1;endExit a while loop at any time using the break statement.while Statements and Empty ArraysA while condition that reduces to an empty array represents a false condition.That is,while A, S1, endnever executes statement S1 when A is an empty array.17-3917M-File ProgrammingforThe for loop executes a statement or group of statements a predeterminednumber of times.















