我想在 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
但不幸的是,它不起作用。不要在任何情况下输入。你知道我该怎么做吗?
比路易斯·门多的答案简单一点,只需使用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
问题是{0:10}
不是{0,1,...,10}
,而是{[0,1,...,10]}
。所以它是一个包含向量的单个单元格,当然x
永远不会等于那个向量。
要解决这个问题,请使用每个单元格一个元素的单元格数组。要从向量创建它们,您可以使用mat2cell
(或者更好的是num2cell
,如@thewaywewalk的答案)
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
s 而不是 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
更干净的解决方案是将 switch 设置为 true。我一直使用这种方法,因为"开关"结构比"if then else"结构更容易阅读。
例如:
i = randi(100);
switch true
case any(i==1:50)
statement
case any(i==51:100)
statement
end