Switch -- How to specify interval of cases?

120 ビュー (過去 30 日間)
Martin
Martin 2012 年 4 月 5 日
コメント済み: Walter Roberson 2018 年 6 月 25 日
Hi, I am writing a SWITCH statement, but I need each case to be chosen for an interval of the switch variable. I'd think this should be obvious, but I'm a bit lost. I know I can specify multiple values in the '{}', but I have too many to specify one by one. How can I incorporate something like case '1:100' ?
Here's an example of what I am trying to accomplish
switch i
case 1:100
statement
case 101:200
statement
end
I tried with {[1:100]} and various variations, but to no avail. I suppose I can create an if statement assigning a 'j' variable to 1 if 1<=i<=100 and then switch over j (so it would be case 1 and case 2), but that seems a bit too inefficient!
Any help?
thank you!

採用された回答

G A
G A 2012 年 4 月 5 日
switch i
case num2cell(1:100)
statement
case num2cell(101:200)
statement
end
  1 件のコメント
Martin
Martin 2012 年 4 月 6 日
doh..!
thank you

サインインしてコメントする。

その他の回答 (2 件)

Mark Brandon
Mark Brandon 2018 年 6 月 25 日
編集済み: Mark Brandon 2018 年 6 月 25 日
Much cleaner solution is to set switch to true. I use this approach all the time given that the "switch" construction is easier to read than the "if then else" construction.
For the example here:
switch true
case any(i==1:100)
statement
case any(i==101:200)
statement
end
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 6 月 25 日
Variants that can be more efficient:
switch true
case ismember(i, 1:100)
statement
case i>=101 && i<=200
statement
end

サインインしてコメントする。


Martin
Martin 2012 年 4 月 5 日
..ok, in fact I can do what I need with if:
if (i>=1)&&(i<=100)
statement
elseif (i>=101)&&(i<=200)
statement
end
Is there no way of doing this with SWITCH?

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by