0
0
MATLABdata~20 mins

Vectorization vs loops in MATLAB - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Vectorization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of vectorized vs loop sum
What is the output of the following MATLAB code snippet?
MATLAB
A = 1:5;
loop_sum = 0;
for i = 1:length(A)
    loop_sum = loop_sum + A(i);
end
vector_sum = sum(A);
disp([loop_sum, vector_sum]);
A[15 15]
B[10 15]
C[15 10]
D[0 15]
Attempts:
2 left
💡 Hint
Think about how sum and loops accumulate values.
Predict Output
intermediate
2:00remaining
Result of element-wise multiplication
What is the output of this MATLAB code?
MATLAB
A = [1 2 3];
B = [4 5 6];
for i = 1:length(A)
    C(i) = A(i) * B(i);
end
disp(C);
A[1 2 3]
B[5 7 9]
C[24 30 36]
D[4 10 18]
Attempts:
2 left
💡 Hint
Multiply each pair of elements at the same position.
Predict Output
advanced
3:00remaining
Vectorized vs loop matrix multiplication output
What is the output of this MATLAB code?
MATLAB
A = [1 2; 3 4];
B = [5 6; 7 8];
C = zeros(2);
for i = 1:2
    for j = 1:2
        for k = 1:2
            C(i,j) = C(i,j) + A(i,k)*B(k,j);
        end
    end
end
D = A*B;
disp(C);
disp(D);
A
[[19 22]; [43 50]]
[[19 22]; [43 50]]
B
[[17 20]; [39 46]]
[[19 22]; [43 50]]
C
[[19 22]; [43 50]]
[[17 20]; [39 46]]
D
[[0 0]; [0 0]]
[[19 22]; [43 50]]
Attempts:
2 left
💡 Hint
Matrix multiplication sums products of rows and columns.
Predict Output
advanced
3:00remaining
Performance difference in vectorized vs loop sum
Which statement about the output of this MATLAB code is true?
MATLAB
N = 1e7;
A = ones(1,N);

% Timing loop sum
tic
s1 = 0;
for i = 1:N
    s1 = s1 + A(i);
end
t_loop = toc;

% Timing vectorized sum
tic
s2 = sum(A);
t_vec = toc;

fprintf('Loop time: %.4f, Vector time: %.4f\n', t_loop, t_vec);
ALoop sum is significantly faster than vectorized sum.
BBoth times are about the same.
CVectorized sum is significantly faster than loop sum.
DCode will produce an error due to large N.
Attempts:
2 left
💡 Hint
Think about how MATLAB optimizes vector operations.
🧠 Conceptual
expert
2:00remaining
Why vectorization is preferred over loops in MATLAB?
Which of the following is the main reason MATLAB users prefer vectorized code over loops?
AVectorized code is easier to read but slower to execute.
BVectorized code runs faster because MATLAB is optimized for matrix and vector operations.
CLoops are deprecated in MATLAB and cannot be used anymore.
DLoops cause syntax errors in MATLAB.
Attempts:
2 left
💡 Hint
Think about MATLAB's design focus on matrices and vectors.