| Programming and Data Types | ![]() |
if evaluates a logical expression and executes a group of statements based on the value of the expression. In its simplest form, its syntax is
iflogical_expressionstatementsend
If the logical expression is true (1), MATLAB executes all the statements between the if and end lines. It resumes execution at the line following the end statement. If the condition is false (0), MATLAB skips all the statements between the if and end lines, and resumes execution at the line following the end statement.
if rem(a,2) == 0
disp('a is even')
b = a/2;
end
You can nest any number of if statements.
If the logical expression evaluates to a nonscalar value, all the elements of the argument must be nonzero. For example, assume X is a matrix. Then the statement
if X
statements
end
if all(X(:))
statements
end
The else and elseif statements further conditionalize the if statement:
else statement has no logical condition. The statements associated with it execute if the preceding if (and possibly elseif condition) is false (0).elseif statement has a logical condition that it evaluates if the preceding if (and possibly elseif condition) is false (0). The statements associated with it execute if its logical condition is true (1). You can have multiple 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;
else
A = (n+1)/2; % If n positive and odd, increment and divide.
end
if Statements and Empty Arrays
An if condition that reduces to an empty array represents a false condition. That is,
if A S1 else S0 end
will execute statement S0 when A is an empty array.
| Flow Control | switch | ![]() |