0
0
MATLABdata~10 mins

Nested loops in MATLAB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Nested loops
Start Outer Loop i=1
Start Inner Loop j=1
Execute Inner Loop Body
Update j = j+1
Check j <= max_j?
NoEnd Inner Loop
Yes
Update i = i+1
Check i <= max_i?
NoEnd Outer Loop
Back to Inner Loop Body
The outer loop runs first. For each outer loop step, the inner loop runs completely. Then the outer loop moves to the next step.
Execution Sample
MATLAB
for i = 1:2
    for j = 1:3
        disp([i, j])
    end
end
Print pairs of i and j where i goes 1 to 2 and j goes 1 to 3 for each i.
Execution Table
StepijCondition i<=2Condition j<=3ActionOutput
111TrueTruePrint [1 1][1 1]
212TrueTruePrint [1 2][1 2]
313TrueTruePrint [1 3][1 3]
414TrueFalseExit inner loop
521TrueTruePrint [2 1][2 1]
622TrueTruePrint [2 2][2 2]
723TrueTruePrint [2 3][2 3]
824TrueFalseExit inner loop
931FalseTrueExit outer loop
💡 i reaches 3, condition i<=2 is False, so outer loop ends
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7After 8Final
i1111222233
j1234123411
Key Moments - 3 Insights
Why does the inner loop restart j from 1 for each new i?
Because the inner loop is inside the outer loop, it runs fully for each i. See execution_table rows 1-4 for i=1 and rows 5-8 for i=2, where j resets to 1 each time.
When does the outer loop variable i increase?
After the inner loop finishes all its iterations. Look at execution_table row 4 where j=4 ends inner loop, then i increments from 1 to 2 at row 5.
Why does the loop stop at i=3?
Because the outer loop condition i<=2 becomes false at i=3, stopping the loop. See execution_table row 9 where condition i<=2 is False.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of j at step 6?
A2
B3
C1
D4
💡 Hint
Check the 'j' column in execution_table row 6.
At which step does the inner loop end for i=1?
AStep 3
BStep 4
CStep 5
DStep 9
💡 Hint
Look for when 'Condition j<=3' becomes False for i=1 in execution_table.
If the outer loop changed to i=1:3, how many total print outputs would there be?
A6
B9
C12
D3
💡 Hint
Multiply outer loop count (3) by inner loop count (3) to find total prints.
Concept Snapshot
Nested loops run one loop inside another.
Outer loop runs first.
For each outer step, inner loop runs fully.
Use nested for loops in MATLAB like:
for i=1:n
  for j=1:m
    % code
  end
end
Inner loop resets each outer iteration.
Full Transcript
Nested loops in MATLAB mean one loop runs inside another. The outer loop variable i starts at 1 and goes to 2. For each i, the inner loop variable j runs from 1 to 3. Each pair (i,j) is printed. The inner loop finishes all j values before i increases. When i reaches 3, the outer loop stops because the condition i<=2 is false. Variables i and j change as the loops run. The inner loop resets j to 1 for each new i. This pattern lets you do repeated tasks in a grid or matrix style.