0
0
MATLABdata~10 mins

Nested loops in MATLAB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a nested loop that prints numbers 1 to 3 for both loops.

MATLAB
for i = 1:3
    for j = 1:[1]
        disp([i, j])
    end
end
Drag options to blanks, or click blank then click option'
A4
B2
C3
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different range for the inner loop causing fewer or more iterations.
2fill in blank
medium

Complete the code to sum all elements in a 2D matrix using nested loops.

MATLAB
total = 0;
for row = 1:size(matrix, 1)
    for col = 1:size(matrix, [1])
        total = total + matrix(row, col);
    end
end
Drag options to blanks, or click blank then click option'
A4
B1
C3
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using size(matrix, 1) for columns which is actually rows.
3fill in blank
hard

Fix the error in the nested loops that print the multiplication table from 1 to 5.

MATLAB
for i = 1:5
    for j = 1:[1]
        fprintf('%d x %d = %d\n', i, j, i*j);
    end
end
Drag options to blanks, or click blank then click option'
A5
B3
C6
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using a smaller range in the inner loop causing incomplete output.
4fill in blank
hard

Fill both blanks to create a nested loop that fills a matrix with the product of its indices.

MATLAB
rows = 3;
cols = 4;
result = zeros(rows, cols);
for r = 1:[1]
    for c = 1:[2]
        result(r, c) = r * c;
    end
end
Drag options to blanks, or click blank then click option'
Arows
Bcols
C4
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping rows and columns in the loops.
5fill in blank
hard

Fill all three blanks to create a nested loop that counts how many elements in a matrix are greater than 10.

MATLAB
count = 0;
for i = 1:[1]
    for j = 1:[2]
        if matrix(i, j) [3] 10
            count = count + 1;
        end
    end
end
Drag options to blanks, or click blank then click option'
Asize(matrix, 1)
Bsize(matrix, 2)
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong size dimensions or wrong comparison operator.