using greater than or less than in 'switch' and 'case' expressions

179 ビュー (過去 30 日間)
Harry
Harry 2013 年 6 月 27 日
回答済み: Walter Roberson 2023 年 4 月 12 日
I don't quite understand how to use the switch and case expressions to calculate when a variable is less than or greater than a particular value. Something like this:
x = 7
switch x
case > 5
disp ('x is greater than 5')
case < 5
disp ('x is less than 5')
otherwise
disp ('error')
  1 件のコメント
zhyar
zhyar 2023 年 4 月 12 日
you can not write case >5 it will give you error

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2013 年 6 月 27 日
use if...elseif..else..end
if x > 5
disp ('x is greater than 5')
elseif x < 5
disp ('x is less than 5')
else
disp ('error')
end

その他の回答 (2 件)

Tom
Tom 2013 年 6 月 27 日
inequalities are best used with IF statements rather than switch; switch is useful for handling a variety of known values.
If you wanted to write it using a switch statement, it might be like this:
switch n
case num2cell(1:4)
disp('n is less than 5')
case num2cell(6:10)
disp('n is greater than 5')
otherwise
disp('error')
end
But clearly this only works for values of n between 1 and 10.

Walter Roberson
Walter Roberson 2023 年 4 月 12 日
x = 7
switch true
case x > 5
disp ('x is greater than 5')
case x < 5
disp ('x is less than 5')
otherwise
disp ('error')
end

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by