switch - Execute one of several groups of statements - MATLAB (original) (raw)

switch, case, otherwise

Execute one of several groups of statements

Syntax

switch switchexpression case caseexpression statements case caseexpression statements ... otherwise statements end

Description

switch _`switchexpression`_, case _`caseexpression`_, end evaluates an expression and chooses to execute one of several groups of statements. Each choice is a case.

The switch block tests each case until one of the case expressions is true. A case is true when:

When a case expression is true, MATLABĀ® executes the corresponding statements and exits the switch block.

An evaluated switchexpression must be a scalar or character vector. An evaluated caseexpression must be a scalar, a character vector, or a cell array of scalars or character vectors.

The otherwise block is optional. MATLAB executes the statements only when no case is true.

example

Examples

collapse all

Display different text conditionally, depending on a value entered at the command prompt.

n = input('Enter a number: ');

switch n case -1 disp('negative one') case 0 disp('zero') case 1 disp('positive one') otherwise disp('other value') end

At the command prompt, enter the number 1.

Repeat the code and enter the number 3.

Determine which type of plot to create based on the value of plottype. If plottype is either 'pie' or 'pie3', create a 3-D pie chart. Use a cell array to contain both values.

x = [12 64 24]; plottype = 'pie3';

switch plottype case 'bar' bar(x) title('Bar Graph') case {'pie','pie3'} pie3(x) title('Pie Chart') otherwise warning('Unexpected plot type. No plot created.') end

Figure contains an axes object. The hidden axes object with title Pie Chart contains 12 objects of type patch, surface, text.

Tips

end

end

Extended Capabilities

expand all

Usage notes and limitations:

Version History

Introduced before R2006a