Understanding switch and case expressions

1 次查看(过去 30 天)
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');

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Financial Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by