Difference between switch and if
Show older comments
2 Comments
Jonas
on 21 Apr 2021
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
on 21 Apr 2021
Accepted Answer
More Answers (1)
Image Analyst
on 21 Apr 2021
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.
1 Comment
Bob Thompson
on 21 Apr 2021
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!