MATLAB switch case Statement
🔁 MATLAB switch case Statement
It is a clean alternative to multiple if–elseif statements, especially when comparing one variable against many values.
MATLAB is developed by MathWorks.
🔹 What Is switch–case?
-
Evaluates one expression
-
Matches it against different cases
-
Executes the matching case block
-
If no case matches →
otherwiseruns
1️⃣ Basic switch–case Syntax
📌 end is mandatory.
2️⃣ Simple Example
Output
3️⃣ Using Multiple Values in One Case
Output
4️⃣ switch–case with Strings
Output
📌 Works with strings and characters.
5️⃣ switch–case Without otherwise
Output
📌 otherwise is optional but recommended.
6️⃣ Menu-Based Example
Output
⚠️ Important Rules
-
Expression is evaluated once
-
Uses exact matching (
==not required) -
No
breakneeded (unlike C/C++) -
casevalues must be unique
🎯 Interview Questions: MATLAB switch–case
🔹 Q1. What is the use of switch–case in MATLAB?
Answer:
To perform multi-way decision making.
🔹 Q2. Difference between if–elseif and switch–case?
Answer:switch–case is cleaner and faster for multiple fixed comparisons.
🔹 Q3. Is break required in MATLAB switch?
Answer:
No, MATLAB automatically breaks after matching case.
🔹 Q4. Can we use strings in switch–case?
Answer:
Yes, MATLAB supports strings and characters.
🔹 Q5. What happens if no case matches?
Answer:otherwise block executes (if present).
🔹 Q6. Can multiple values be used in one case?
Answer:
Yes, using cell array {}.
🔹 Q7. Is otherwise mandatory?
Answer:
No, but recommended.
✅ Summary
-
Used for multi-condition checks
-
Cleaner than multiple
if–elseif -
No
breakneeded -
Supports numbers & strings
