在MATLAB中使用带有多个选项的开关

时间:2014-03-02 14:49:43

标签: matlab switch-statement

我想在Matlab中得到类似的内容:

x = round(rand*10);
switch (x)
    case {0:10}
        disp('x between 0 and 10');
    case {11:20}
        disp('x between 11 and 20');
    case {21:100}
        disp('x between 21 and 100');
end

但遗憾的是它不起作用。不要输入任何案件。你知道我怎么能这样做吗?

3 个答案:

答案 0 :(得分:4)

比Luis Mendo的答案简单一点,只需使用num2cell将双打矩阵转换为双精度数组。

x = randi(100);

switch (x)
    case num2cell(0:10)
        disp('x between 0 and 10');
    case num2cell(11:20)
        disp('x between 11 and 20');
    case num2cell(21:100)
        disp('x between 21 and 100');
end

答案 1 :(得分:3)

问题是{0:10}不是{0,1,...,10},而是{[0,1,...,10]}。所以它是一个包含向量的单个单元格,当然x永远不会等于向量

要解决此问题,请使用每个单元格包含一个元素的单元格数组。要从矢量创建它们,您可以使用mat2cell(或更好num2cell,如@thewaywewalk's answer中所示)

x = round(rand*10);
switch (x)
    case mat2cell(0:10,1,ones(1,11))
        disp('x between 0 and 10');
    case mat2cell(11:20,1,ones(1,11))
        disp('x between 11 and 20');
    case mat2cell(21:100,1,ones(1,81))
        disp('x between 21 and 100');
end

或者,更轻松地使用elseif而不是switch,然后您可以使用向量和any

x = round(rand*10);
if any(x==0:10)
    disp('x between 0 and 10');
elseif any(x==11:20)
    disp('x between 11 and 20');
elseif any(x==21:80)
    disp('x between 21 and 100');
end

答案 2 :(得分:0)

更清洁的解决方案是将switch设置为true。鉴于“ switch”构造比“ if then else”构造更易于阅读,因此我一直使用这种方法。

例如:

i = randi(100);
switch true
    case any(i==1:50)
        statement
    case any(i==51:100)
        statement
end