Difference between switch and if
이전 댓글 표시
댓글 수: 2
Jonas
2021년 4월 21일
i think in matlab there is no difference between switch and many if/elseif statements. the switch is also known in many other programming languages, but behaves a bit differently than in matlab. in matlab the corresponding case is executed and the code continues behind the block, in other languages the switch block is exited only if there is a break at the end of the case, otherwise other cases would be tested too. i hope i remebered correctly, it has been some time since my last c++ session
Bob Thompson
2021년 4월 21일
채택된 답변
추가 답변 (1개)
Image Analyst
2021년 4월 21일
They're pretty much the same, just slightly different syntax as to how to get the condition. Switch requires an extra line of code than if but that's no big deal.
switch(value)
case 1
% code
otherwise
% code
end % 4 lines of code
if value == 1
% code
else
%code
end % 3 lines of code
Use which ever one you think makes it easier to read your code. If the condition needs to be made up from multiple tests/operations, then it might be better in an if. switch is best for situations where the condition is just a single value (number, string), or cell array of several such values.
value = (blah + fubar) * snafu
switch(value)
case 1
% code
case {2, 3}
% code
otherwise
% code
end
if (blah + fubar) * snafu == 1
% code
elseif (blah + fubar) * snafu == 2 && (someOtherVariable == 3) % Hard to do with "case"
% code
end
My two cents worth, for what it's worth.
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!