MATLAB for Loop

MATLAB Tutorial

🔁 MATLAB for Loop

The for loop in MATLAB is used to repeat a block of code a fixed number of times.

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

1
2
3
4
5

3️⃣ for Loop with Step Size


Output

1
3
5
7
9

4️⃣ Using for Loop with Arrays


 

Output

10
20
30
40

5️⃣ Sum of Numbers Using for Loop


 

Output

15

6️⃣ Nested for Loop

A loop inside another loop (used for matrices).


Output

1 2 3
2 4 6
3 6 9

7️⃣ for Loop with Matrix


 

Output

1
2
3
4

⚠️ Important Rules

  • end is 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

  • for loop repeats code for a known range

  • Works with numbers, vectors, matrices

  • Supports nested loops

  • Essential for iterative logic

You may also like...