[英]How to change if else to switch case
I have this code at the moment 我现在有这段代码
s=[1 3 4 9 12 16 18 19 20 21];
for k=s
if k>2 & k<10
a(k)=0;
else if k>10 & k<20
a(k)=1;
else a(k)=2;
end
end
end
I would like to rewrite this using a switch, case
statement. 我想使用
switch, case
语句重写它。 How can I do this? 我怎样才能做到这一点?
According to the documentation you can use cell arrays in case
expression. 根据文档,您可以在
case
表达式中使用单元格数组。
for k=s
switch k
case num2cell(3:9)
a(k)=0;
case num2cell(11:19)
a(k)=1;
otherwise
a(k)=2;
end
end
However you often do not want to use if/else or switch/case instead you can use indexing: 但是,您通常不希望使用if / else或switch / case,而可以使用索引:
a(s) = 2;
a(s(s>2 & s<10)) = 0;
a(s(s>10 & s<20)) = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.