Write a Python function that takes as input three integers, M, N, and r, and returns an MN matrix of rank r. Create matrices of different sizes and ranks, and use numpy.linalg.matrix_rank() to verify the returned matrices have the desired rank.
Why should you expect a randomly generated matrix to have the rank you prescribe? What happens if you set r > min(M, N), and why does that happen?
def randrank(M, N, r):
A = random.randn(M, r)
B = random.randn(N, r)
return A.dot(B.T)
R = randrank(32, 41, 7)
print(R.shape, ‘\n’)
print(LA.matrix_rank(R), ‘\n’)
(32, 41)
7
(a) Use the function in Exercise #1 to generate a 5020 random matrix of rank r = 20, and visualize it.
(b) Find the SVD of the matrix in part (a) using numpy.linalg.svd().
(c) Reconstruct the MN 2D array s with the entries of along its diagonal and zeros everywhere else:
S = [s100000, s200000, sN00] if M > N, or
S = [s1000, s2000, sM000000] if M < N
(d) Verify that U.dot(S.dot(Vt)) recovers the matrix created in part (a).
(e) Repeat (a) - (d) for a randomly generated 2050 matrix of rank r = 20.