Challenge - 5 Problems
Vectorization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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]);
Attempts:
2 left
💡 Hint
Think about how sum and loops accumulate values.
✗ Incorrect
Both the loop and the vectorized sum compute the sum of elements 1 through 5, which is 15.
❓ Predict Output
intermediate2: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);
Attempts:
2 left
💡 Hint
Multiply each pair of elements at the same position.
✗ Incorrect
Each element of C is the product of corresponding elements in A and B: 1*4=4, 2*5=10, 3*6=18.
❓ Predict Output
advanced3: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);
Attempts:
2 left
💡 Hint
Matrix multiplication sums products of rows and columns.
✗ Incorrect
Both the loop and the vectorized multiplication produce the same matrix [[19 22]; [43 50]].
❓ Predict Output
advanced3: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);
Attempts:
2 left
💡 Hint
Think about how MATLAB optimizes vector operations.
✗ Incorrect
Vectorized operations in MATLAB are optimized and run faster than explicit loops for large arrays.
🧠 Conceptual
expert2:00remaining
Why vectorization is preferred over loops in MATLAB?
Which of the following is the main reason MATLAB users prefer vectorized code over loops?
Attempts:
2 left
💡 Hint
Think about MATLAB's design focus on matrices and vectors.
✗ Incorrect
MATLAB is designed to efficiently handle vector and matrix operations internally, making vectorized code faster.