MATLAB if Statement
🔀 MATLAB if Statement
It allows MATLAB to execute code only when a condition is true.
MATLAB is developed by MathWorks.
🔹 What Is an if Statement?
The if statement checks a logical condition:
-
If the condition is true (1) → code executes
-
If the condition is false (0) → code is skipped
1️⃣ Basic if Statement
🔸 Syntax
🔸 Example
Output
2️⃣ if–else Statement
🔸 Syntax
🔸 Example
Output
3️⃣ if–elseif–else Statement
🔸 Syntax
🔸 Example
Output
4️⃣ Nested if Statement
An if statement inside another if.
Output
5️⃣ Using Logical Operators in if
Output
📌 Use && and || for scalar conditions.
⚠️ Important Rules
-
Condition must return a logical value
-
Always close with
end -
MATLAB is case-sensitive
-
Prefer
&&,||insideif
🎯 Interview Questions: MATLAB if Statement
🔹 Q1. What is the use of if statement in MATLAB?
Answer:
To execute code only when a condition is true.
🔹 Q2. What type of value does an if condition require?
Answer:
A logical value (true or false).
🔹 Q3. Difference between & and && in if?
Answer:& is element-wise, && is short-circuit and recommended for if.
🔹 Q4. Is end mandatory in if statement?
Answer:
Yes, every if block must end with end.
🔹 Q5. Can we use relational operators inside if?
Answer:
Yes (>, <, ==, ~= etc.).
🔹 Q6. What happens if condition is false?
Answer:
The code inside if block is skipped.
🔹 Q7. Can we nest if statements?
Answer:
Yes, MATLAB supports nested if.
✅ Summary
-
ifcontrols decision making -
Executes code based on conditions
-
Supports
if,if–else,elseif -
Essential for logical programming
