Challenge - 5 Problems
Matrix Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of matrix multiplication with SciPy
What is the output of the following code that multiplies two sparse matrices?
SciPy
import numpy as np from scipy.sparse import csr_matrix A = csr_matrix(np.array([[1, 0, 2], [0, 3, 0]])) B = csr_matrix(np.array([[0, 3], [1, 0], [4, 5]])) C = A.dot(B) print(C.toarray())
Attempts:
2 left
💡 Hint
Remember that matrix multiplication sums the products of row elements of A with column elements of B.
✗ Incorrect
Matrix multiplication of A and B results in a 2x2 matrix. For example, element (0,0) is 1*0 + 0*1 + 2*4 = 8, and element (0,1) is 1*3 + 0*0 + 2*5 = 13.
❓ data_output
intermediate1:30remaining
Shape and type of a sparse matrix
After running this code, what are the shape and type of the matrix M?
SciPy
from scipy.sparse import lil_matrix M = lil_matrix((3, 4)) M[1, 2] = 5 M[2, 3] = 10 print(M.shape, type(M))
Attempts:
2 left
💡 Hint
The shape is set when creating the matrix. The type depends on the sparse format used.
✗ Incorrect
The matrix M is created with shape (3,4) using lil_matrix, so its type is scipy.sparse.lil_matrix and shape is (3,4).
🔧 Debug
advanced1:30remaining
Identify the error in matrix addition
What error will this code raise when adding two sparse matrices of different shapes?
SciPy
from scipy.sparse import csr_matrix A = csr_matrix([[1, 2], [3, 4]]) B = csr_matrix([[5, 6, 7], [8, 9, 10]]) C = A + B
Attempts:
2 left
💡 Hint
Check if the shapes of the matrices are compatible for addition.
✗ Incorrect
Adding sparse matrices requires them to have the same shape. Here, A is 2x2 and B is 2x3, so a ValueError about dimension mismatch is raised.
❓ visualization
advanced2:00remaining
Visualizing a sparse matrix
Which option correctly creates a visualization of the nonzero elements of a sparse matrix using matplotlib?
SciPy
import matplotlib.pyplot as plt from scipy.sparse import coo_matrix row = [0, 1, 2, 0] col = [0, 2, 2, 1] data = [4, 5, 7, 9] M = coo_matrix((data, (row, col)), shape=(3, 3)) plt.figure() # Fill in the missing code here plt.show()
Attempts:
2 left
💡 Hint
Use a function designed to show sparsity patterns.
✗ Incorrect
plt.spy() is designed to visualize the sparsity pattern of a matrix, showing nonzero elements clearly.
🧠 Conceptual
expert2:30remaining
Memory efficiency of sparse matrix formats
Which sparse matrix format is generally most memory efficient for fast arithmetic operations on large, sparse matrices?
Attempts:
2 left
💡 Hint
Consider which format is optimized for arithmetic and slicing.
✗ Incorrect
CSR format stores data efficiently and supports fast arithmetic and matrix-vector operations, making it best for large sparse matrices.