我的if-else语句/ switch case语句不能正常工作

时间:2014-06-02 23:19:36

标签: matlab if-statement switch-statement

我无法获得if-else语句/ switch case语句。我有一个数字,需要查找它是否在一组值或另一组值之间。我尝试了各种配置,没有任何工作。 (下面的配置示例,PS节省空间我只显示每个配置2个案例,但我有15个)

date = 1204 or 1203

switch (date)
    case {(1204:1211),(0602:0610)} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {(1126:1203),(0611:0618)} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end    


switch (date)
    case {1204:1211,0602:0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126:1203,0611:0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end  

switch (date)
    case {1204 <= date && date >= 1211,0602 <= date && date >= 0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126 <= date && date >= 1203,0611 <= date && date >= 0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end 

switch (date)
    case {1204 <= date && date >= 1211 || 0602 <= date && date >= 0610} % (Dec 4-11th) && (Jun 2-10th)
        d = 0;
    case {1126 <= date && date >= 1203 || 0611 <= date && date >= 0618} % (Nov 26th - Dec 3rd) && (Jun 11-18th)
        d = 1;
    otherwise
        d = 11;
end 

if 1204 <= date && date >= 1211 || 0602 <= date && date >= 0610 % (Dec 4-11th) && (Jun 2-10th)
    d = 0;
elseif 1126 <= date && date >= 1203 || 0611 <= date && date >= 0618 % (Nov 26th - Dec 3rd) && (Jun 11-18th)
    d = 1;
else    
    d = 11;
end 

1 个答案:

答案 0 :(得分:2)

我认为你不能在case表达式中使用条件函数。相反,请使用if / elseif / else构造:

if (1204<=date && date<=1211) || (0602<=date && date<=0610) % (Dec 4-11th) && (Jun 2-10th)
    d = 0;
elseif (1126 <= date && date <= 1203) || (0611 <= date && date <= 0618) % (Nov 26th - Dec 3rd) && (Jun 11-18th)
    d = 1;
else
    d = 11;
end

来自the documentation

  

case_expression不能包含<>等关系运算符   与switch_expression进行比较。要测试不平等,请使用   if - elseif语句。