MATLAB Function Reference | Search  Help Desk |
if | Examples See Also |
Conditionally execute statements
ifexpression
statements
end ifexpression1
statements
elseifexpression2
statements
elsestatements
end
if
conditionally executes statements.
The simple form is:
ifMore complicated forms useexpression
statements
end
else
or elseif
. Each if
must be paired with a matching end
.
Here is an example showing if
, else
, and elseif
:
for i = 1:n for j = 1:n if i == j a(i,j) = 2; elseif abs([i j]) == 1 a(i,j) = 1; else a(i,j) = 0; end end endSuch expressions are evaluated as false unless every element-wise comparison evaluates as true. Thus, given matrices
A
and B
:
A = B = 1 0 1 1 2 3 3 4The expression:
break
Terminate execution of for or while loop
else
Conditionally execute statements
end
Terminate for, while, switch, try, and if statements
or indicate last index
for
Repeat statements a specific number of times
return
Return to the invoking function
switch
Switch among several cases based on expression
while
Repeat statements an indefinite number of times