Nested loops in MATLAB - Time & Space Complexity
When we use nested loops, the program repeats actions inside another repeated action. This can make the program take longer as the input grows.
We want to know how much longer the program takes when the input size gets bigger.
Analyze the time complexity of the following code snippet.
n = 5;
for i = 1:n
for j = 1:n
disp(i * j);
end
end
This code prints the product of two numbers for every pair from 1 to n, using two loops inside each other.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop runs a print command for each pair (i, j).
- How many times: The outer loop runs n times, and for each outer loop, the inner loop runs n times, so total n x n times.
As n grows, the total number of print actions grows by n times n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: When n doubles, the operations become about four times more, showing a square growth.
Time Complexity: O(n^2)
This means the time it takes grows roughly with the square of the input size.
[X] Wrong: "The inner loop only adds a little extra time, so the total time is just twice as long as one loop."
[OK] Correct: Because the inner loop runs completely for each outer loop step, the total work multiplies, not just adds.
Understanding nested loops helps you explain how programs handle repeated tasks inside other repeated tasks, a common pattern in coding challenges and real projects.
"What if the inner loop ran only half as many times as the outer loop? How would the time complexity change?"
Practice
for i = 1:2
for j = 1:3
disp([i, j])
end
endSolution
Step 1: Understand the loop structure
The outer loop runs with i from 1 to 2, and inside it, the inner loop runs with j from 1 to 3.Step 2: Identify nested loop behavior
For each i, the inner loop runs fully for all j values, repeating tasks multiple times.Final Answer:
Runs one loop inside another to repeat tasks multiple times -> Option AQuick Check:
Nested loops repeat inner loop for each outer loop iteration [OK]
- Thinking loops run sequentially without nesting
- Confusing nested loops with single combined loops
- Assuming loops stop early without completing inner loop
Solution
Step 1: Check proper loop nesting and end statements
for i = 1:3 for j = 1:2 disp(i+j) end end correctly nests the inner loop inside the outer loop and closes both withend.Step 2: Identify syntax errors in other options
The other options miss proper indentation or have missingendstatements causing syntax errors.Final Answer:
for i = 1:3 for j = 1:2 disp(i+j) end end -> Option DQuick Check:
Proper nested loops need matchingendfor eachfor[OK]
- Missing end for inner or outer loop
- Incorrect indentation causing confusion
- Starting loops without proper nesting
for i = 1:2
for j = 1:2
fprintf('%d ', i*j)
end
fprintf('\n')
endSolution
Step 1: Calculate inner loop outputs for each outer loop value
When i=1, j=1:2, outputs are 1*1=1 and 1*2=2. When i=2, j=1:2, outputs are 2*1=2 and 2*2=4.Step 2: Format output with new lines
Each inner loop prints values with space, then outer loop prints newline. So output lines are '1 2 ' and '2 4 '.Final Answer:
1 2 2 4 -> Option CQuick Check:
Multiply i and j in nested loops for output [OK]
- Ignoring newline after inner loop
- Mixing up i and j values
- Printing all values in one line
for i = 1:3
for j = 1:2
disp(i+j)
endSolution
Step 1: Check loop endings
The inner loop has anend, but the outer loop does not have its closingend.Step 2: Identify syntax error cause
Missing the outer loop'sendcauses MATLAB to throw an error.Final Answer:
Missing end for outer loop -> Option AQuick Check:
Each for loop needs its own end [OK]
- Forgetting to close outer loop
- Assuming one end closes both loops
- Misreading error messages
Solution
Step 1: Understand the multiplication table goal
The table should store products of row and column indices, so M(i,j) = i*j.Step 2: Check each option's assignment
M = zeros(3); for i = 1:3 for j = 1:3 M(i,j) = i*j; end end correctly assigns M(i,j) = i*j. The other options assign sums or differences, not products.Final Answer:
M = zeros(3); for i = 1:3 for j = 1:3 M(i,j) = i*j; end end -> Option BQuick Check:
Multiplication table uses product of indices [OK]
- Using addition or subtraction instead of multiplication
- Swapping indices in assignment
- Not initializing matrix before loops
Ready to prove it?
Pass the test and this pattern moves unknown
