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?
0 个评论
采纳的回答
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
2013-3-12
Joe this behavior is explained in the doc:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Financial Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!