Programming Previous page   Next Page

Conditional Control -- if, switch

This group of control statements enables you to select at run-time which block of code is executed. To make this selection based on whether a condition is true or false, use the if statement (which may include else or elseif). To select from a number of possible options depending on the value of an expression, use the switch and case statements (which may include otherwise).

if, else, and elseif

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

If the logical expression is true (that is, if it evaluates to logical 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 (evaluates to logical 0), MATLAB skips all the statements between the if and end lines, and resumes execution at the line following the end statement.

For example,

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

is equivalent to

The else and elseif statements further conditionalize the if statement:

if Statements and Empty Arrays.   An if condition that reduces to an empty array represents a false condition. That is,

executes statement S0 when A is an empty array.

switch, case, and otherwise

switch executes certain statements based on the value of a variable or expression. Its basic form is

This block consists of

switch works by comparing the input expression to each case value. For numeric expressions, a case statement is true if (value==expression). For string expressions, a case statement is true if strcmp(value,expression).

The code below shows a simple example of the switch statement. It checks the variable input_num for certain values. If input_num is -1, 0, or 1, the case statements display the value as text. If input_num is none of these values, execution drops to the otherwise statement and the code displays the text 'other value'.

switch can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.


Previous page  Program Control Statements Loop Control -- for, while, continue, break Next page

© 1994-2005 The MathWorks, Inc.