MATLAB for Loop
🔁 MATLAB for Loop
It is commonly used for iterating over arrays, vectors, and matrices.
MATLAB is developed by MathWorks.
🔹 What Is a for Loop?
A for loop runs a set of statements once for each value in a specified range or array.
1️⃣ Basic for Loop Syntax
-
start→ initial value -
step→ increment (optional, default = 1) -
end→ final value
2️⃣ Simple for Loop Example
Output
3️⃣ for Loop with Step Size
Output
4️⃣ Using for Loop with Arrays
Output
5️⃣ Sum of Numbers Using for Loop
Output
6️⃣ Nested for Loop
A loop inside another loop (used for matrices).
Output
7️⃣ for Loop with Matrix
Output
⚠️ Important Rules
-
endis mandatory -
Loop variable is updated automatically
-
MATLAB prefers vectorized operations, but loops are still useful
-
Loop variable exists after the loop ends
🎯 Interview Questions: MATLAB for Loop
🔹 Q1. What is a for loop used for in MATLAB?
Answer:
To repeat a block of code a fixed number of times.
🔹 Q2. What is the default step size in a for loop?
Answer:1
🔹 Q3. Can a for loop iterate over arrays?
Answer:
Yes, using indices or directly over values.
🔹 Q4. Is end mandatory in a for loop?
Answer:
Yes.
🔹 Q5. What is a nested for loop?
Answer:
A for loop inside another for loop.
🔹 Q6. Which is faster in MATLAB: loops or vectorization?
Answer:
Vectorization is generally faster, but loops are still supported.
🔹 Q7. What happens to the loop variable after loop ends?
Answer:
It retains its last value.
✅ Summary
-
forloop repeats code for a known range -
Works with numbers, vectors, matrices
-
Supports nested loops
-
Essential for iterative logic
