天天看点

matlab中的case语句,MATLAB switch语句

本文概述

开关是另一种条件语句, 它执行多个语句组中的一个。

如果我们要根据一组预定义的规则测试相等性, 那么switch语句可以替代if语句。

句法

switch switch_expression

case case_expression1

Statements

case case_expression2

Statements

case case_expressionN

Statements

otherwise

Statements

End

Switch语句流程图

matlab中的case语句,MATLAB switch语句

以下是在MATLAB中使用switch的要点:

类似于if块, switch块会测试每种情况, 直到case_expression之一为true为止。评估为:

case&switch必须等于数字ascase_expression == switch_expression。

对于字符向量, strcmp函数返回的结果必须等于1, 因为-strcmp(case_expression, switch_expression)== 1。

对于对象, case_expression == switch_expression。

对于单元阵列, case_expression中的单元阵列的至少一个元素必须与switch_expression匹配。

switch语句不测试不等式, 因此case_expression不能包含诸如之类的关系运算符以与switch_expression进行比较。

例1

% program to check whether the entered number is a weekday or not

a = input('enter a number : ')

switch a

case 1

disp('Monday')

case 2

disp('Tuesday')

case 3

disp('Wednesday')

case 4

disp('Thursday')

case 5

disp('Friday')

case 6

disp('Saturday')

case 7

disp('Sunday')

otherwise

disp('not a weekday')

end

输出

enter a number: 4

Thursday

例2

% Program to find the weekday of a given date

% take date input from keyboard in the specified format

d = input('enter a date in the format- dd-mmm-yyyy:', "s")

% weekday function takes input argument

% and returns the day number & day name of the particular date.

[dayNumber, dayName] = weekday(d, 'long', "local");

% use switch and case to display the output as per the entered input

switch dayNumber

case 2

x = sprintf('Start of the week-%s-:%d', dayName, dayNumber);

disp(x)

case 3

x = sprintf('%s:%d', dayName, dayNumber);

disp(x)

case 4

x = sprintf('%s:%d', dayName, dayNumber);

disp(x)

case 5

x = sprintf('%s:%d', dayName, dayNumber);

disp(x)

case 6

x = sprintf('Last working day-%s-of the week:%d', dayName, dayNumber);

disp(x)

otherwise

disp('weekend')

end