MATLAB if Statement

MATLAB Tutorial

🔀 MATLAB if Statement 

The if statement in MATLAB is used for decision making.

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

if condition
statements
end

🔸 Example


 

Output

x is greater than 5

2️⃣ if–else Statement

🔸 Syntax

if condition
statements
else
statements
end

🔸 Example


 

Output

Positive number

3️⃣ if–elseif–else Statement

🔸 Syntax

if condition1
statements
elseif condition2
statements
else
statements
end

🔸 Example


 

Output

Pass

4️⃣ Nested if Statement

An if statement inside another if.


 

Output

Eligible to vote

5️⃣ Using Logical Operators in if


 

Output

Eligible for job

📌 Use && and || for scalar conditions.


⚠️ Important Rules

  • Condition must return a logical value

  • Always close with end

  • MATLAB is case-sensitive

  • Prefer &&, || inside if


🎯 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

  • if controls decision making

  • Executes code based on conditions

  • Supports if, if–else, elseif

  • Essential for logical programming

You may also like...