Understanding switch and case expressions

1 回表示 (過去 30 日間)
Joe
Joe 2013 年 3 月 12 日
a = 'hi';
switch a
case {'hi','hello'}
disp('hi, hello')
case 'hi'
disp('hi')
end
When executing this code, the result is hi, hello. This does not make sense to me. If a = 'hi', then according to the case 'hi' shouldn't the result just be hi. Why is it hi, hello?

採用された回答

Ryan Livingston
Ryan Livingston 2013 年 3 月 12 日
編集済み: Ryan Livingston 2013 年 3 月 12 日
The cases are checked in order. Since a = 'hi' and 'hi' is in the first case, that one is chosen.
Using a cell array:
case {'hi', 'hello'}
disp('hi, hello');
means "pick this case if "a" is either 'hi' or 'hello'. It is somewhat equivalent to saying:
if strcmp(a,'hi') || strcmp(a,'hello')
 disp('hi, hello');
  1 件のコメント
Shashank Prasanna
Shashank Prasanna 2013 年 3 月 12 日
Joe this behavior is explained in the doc:

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFinancial Toolbox についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by