0
0
MATLABdata~20 mins

Nested loops in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested loops with matrix assignment
What is the output of the following MATLAB code?
result = zeros(2,3);
for i = 1:2
    for j = 1:3
        result(i,j) = i + j;
    end
end
result
MATLAB
result = zeros(2,3);
for i = 1:2
    for j = 1:3
        result(i,j) = i + j;
    end
end
result
A[2 3 4; 3 4 5]
B[1 2 3; 2 3 4]
C[3 4 5; 4 5 6]
D[1 1 1; 1 1 1]
Attempts:
2 left
💡 Hint
Remember that MATLAB indices start at 1 and the loops assign i + j to each element.
Predict Output
intermediate
2:00remaining
Nested loops with conditional break
What is the value of variable count after running this MATLAB code?
count = 0;
for i = 1:5
    for j = 1:5
        count = count + 1;
        if i * j > 6
            break;
        end
    end
end
count
MATLAB
count = 0;
for i = 1:5
    for j = 1:5
        count = count + 1;
        if i * j > 6
            break;
        end
    end
end
count
A20
B25
C16
D10
Attempts:
2 left
💡 Hint
The inner loop breaks when i*j > 6, so not all inner iterations run fully. Note that count increments before the check.
🔧 Debug
advanced
2:00remaining
Identify the error in nested loops
What error does this MATLAB code produce when run?
for i = 1:3
    for j = 1:3
        disp(i + j
    end
end
MATLAB
for i = 1:3
    for j = 1:3
        disp(i + j
    end
end
ASyntaxError: Missing closing parenthesis
BRuntimeError: Variable j undefined
CIndexError: Index exceeds matrix dimensions
DNo error, outputs sums
Attempts:
2 left
💡 Hint
Check the parentheses in the disp function call.
🧠 Conceptual
advanced
2:00remaining
Number of iterations in nested loops
How many times will the innermost statement run in this MATLAB code?
count = 0;
for i = 1:4
    for j = i:4
        count = count + 1;
    end
end
count
MATLAB
count = 0;
for i = 1:4
    for j = i:4
        count = count + 1;
    end
end
count
A16
B10
C8
D6
Attempts:
2 left
💡 Hint
The inner loop starts at i and goes to 4, so the number of iterations decreases as i increases.
🚀 Application
expert
3:00remaining
Create a multiplication table matrix
Which MATLAB code correctly creates a 5x5 multiplication table matrix M where M(i,j) = i*j using nested loops?
A
M = zeros(5,5);
for i = 1:5
    for j = 1:5
        M(i,j) = i + j;
    end
end
B
M = zeros(5,5);
for i = 1:5
    for j = 1:5
        M(j,i) = i * j;
    end
end
C
M = zeros(5,5);
for i = 1:5
    for j = 1:5
        M(i+j) = i * j;
    end
end
D
M = zeros(5);
for i = 1:5
    for j = 1:5
        M(i,j) = i * j;
    end
end
Attempts:
2 left
💡 Hint
Remember MATLAB matrices are indexed by row and column, and multiplication table means product of indices.