English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The switch block conditionally executes a group of statements from multiple choices, each included in a case statement.
The evaluated switch_expression is a scalar or string.
The evaluated case_expression is a scalar, string, or an array of cells containing a scalar or string.
The switch module will test each case until one of them is valid.
For numberseq(case_expression,switch_expression).
For stringsstrcmp(case_expression,switch_expression).
For supported objectseq(case_expression,switch_expression).
For the cell case_expression, at least one element of the cell matches the switch_expression, as defined above for numbers, strings, and objects.
When the case is true, MATLAB executes the corresponding statements and then exits the switch block.
otherwiseBlocks are optional and are executed only when no cases exist.
The syntax of the switch statement in MATLAB is-
switch <switch_expression> case <case_expression> <statements> case <case_expression> <statements> ... ... otherwise <statements> end
Create a script file and enter the following code-
grade = 'B'; switch(grade) case 'A' fprintf('Excellent!\n'); case 'B' fprintf('Well done\n'); case 'C' fprintf('Well done\n'); case 'D' fprintf('You passed\n'); case 'F' fprintf('Better try again\n'); otherwise fprintf('Invalid grade\n'); endWhen running the file, it displays-
Well done