Understanding switch and case expressions
조회 수: 2 (최근 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!