Difference between two statements

1 回表示 (過去 30 日間)
Fausto Pachecco Martínez
Fausto Pachecco Martínez 2021 年 11 月 18 日
I have a simple question, what's the difference between switch and if? Can you give me an example of a situation where is useful to use the conditional switch?

採用された回答

Adam Danz
Adam Danz 2021 年 11 月 18 日
Good question.
See this discussion and if you have any other questions or comments, let's continue the disucssion.
  1 件のコメント
Fausto Pachecco Martínez
Fausto Pachecco Martínez 2021 年 11 月 18 日
Thanks

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

その他の回答 (1 件)

Dave B
Dave B 2021 年 11 月 18 日
編集済み: Dave B 2021 年 11 月 18 日
Switch doesn't provide new functionality but can make code easier to read and less complex:
a='Apple';
These two blocks do the same thing:
switch lower(a)
case {'apple' 'orange' 'banana'}
t='Fruit';
case {'carrot' 'spinach' 'pea'}
t='Vegetable';
case {'horse' 'cow' 'moose'}
t='Animal'
otherwise
t='unknown'
end
t
t = 'Fruit'
if ismember(lower(a),{'apple' 'orange' 'banana'})
t='Fruit';
elseif ismember(lower(a),{'carrot' 'spinach' 'pea'})
t='Vegetable';
elseif ismember(lower(a),{'horse' 'cow' 'moose'})
t='Animal'
else
t='unknown'
end
t
t = 'Fruit'
An important note: it's not just that the lines are shorter in the second section.
When you enter a switch statement, you know what you're 'switching on' - the logic will only deal with the contents of lower(a). When you enter an if statement with a bunch of branches they have access to everything in the workspace. That means a single if statement can be more flexible, but also more complex. Modifications to things other than the contents of lower(a) can affect the if statement but not the switch, which can be a big advantage in reducing complexity!
(For this reason, if you run checkmcode with the '-modcyc' keyword, you'll see that switch statements are marked as having a reduced complexity score.)
  1 件のコメント
Fausto Pachecco Martínez
Fausto Pachecco Martínez 2021 年 11 月 18 日
Thank you so much!

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

カテゴリ

Help Center および File ExchangeJust for fun についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by