📜  MATLAB开关

📅  最后修改于: 2021-01-07 02:13:38             🧑  作者: Mango

MATLAB开关

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

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

句法:

switch switch_expression
    case case_expression1
        Statements
    case case_expression2
        Statements
    case case_expressionN
        Statements    
    otherwise
        Statements
End

Switch语句流程图

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

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

  • case&switch必须等于数字as- case_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