Syntax
Description
else
is used to delineate an alternate block of statements. If expression
evaluates as false
, MATLAB executes the one or more commands denoted here as statements2
.
A true
expression has either a logical true or nonzero value. For nonscalar expressions, (for example, "if (matrix A is less than matrix B)"), true
means that every element of the resulting matrix has a logical true or nonzero value.
Expressions usually involve relational operations such as (count <> or
isreal(A)
. Simple expressions can be combined by logical operators (&
,|
,~
) into compound expressions such as: (count <>= 0)
.
Examples
In this example, if both of the conditions are not satisfied, then the student fails the course.
elseif
Conditionally execute statements
Syntax
Description
If expression1
evaluates as false
and expression2
as true
, MATLAB executes the one or more commands denoted here as statements2
.
A true
expression has either a logical true or nonzero value. For nonscalar expressions, (for example, is matrix A less then matrix B), true
means that every element of the resulting matrix has a logical true or nonzero value.
Expressions usually involve relational operations such as (count <> or
isreal(A)
. Simple expressions can be combined by logical operators (&
,|
,~
) into compound expressions such as: (count <>= 0)
.
Remarks
else
if
, with a space between the else
and the if
, differs from elseif
, with no space. The former introduces a new, nested if
, which must have a matching end
. The latter is used in a linear sequence of conditional statements with only one terminating end
.
The two segments shown below produce identical results. Exactly one of the four assignments to x
is executed, depending upon the values of the three logical expressions, A
, B
, and C
.
if A if A
x = a x = a
else elseif B
if B x = b
x = b elseif C
else x = c
if C else
x = c x = d
else end
x = d
end
end
end
Examples
No comments:
Post a Comment