Introduction
Switch-case statements help you choose what to do based on different possible values. It makes your code cleaner and easier to read than many if-else checks.
Switch-case statements help you choose what to do based on different possible values. It makes your code cleaner and easier to read than many if-else checks.
switch expression
case value1
% code to run if expression == value1
case value2
% code to run if expression == value2
otherwise
% code to run if no case matches
endThe expression is what you check against each case value.
The otherwise part is optional and runs if no cases match.
day. If it is 1, it prints Monday; if 2, Tuesday; otherwise, it prints Other day.switch day
case 1
disp('Monday')
case 2
disp('Tuesday')
otherwise
disp('Other day')
end{'red', 'blue'}.switch color
case {'red', 'blue'}
disp('Primary color')
case 'green'
disp('Secondary color')
endThis program checks the value of choice. Since it is 3, it prints the message for option 3.
choice = 3; switch choice case 1 disp('You chose option 1') case 2 disp('You chose option 2') case 3 disp('You chose option 3') otherwise disp('Invalid choice') end
Each case must be unique; MATLAB matches the first one that fits.
Use otherwise to catch unexpected values and avoid errors.
Switch-case helps select code to run based on a value.
It is cleaner than many if-else statements.
Use otherwise for default actions.
switch-case statement in MATLAB?switch followed by the variable name.color = 'green';
switch color
case 'red'
disp('Stop')
case 'green'
disp('Go')
otherwise
disp('Wait')
endcolor is set to 'green'.disp('Go').value = 10;
switch value
case 5
disp('Five')
case 10
disp('Ten')
case
disp('Other')
end{'Saturday', 'Sunday'}.Pass the test and this pattern moves unknown