DDC-50: Singular values of a diagonal matrix
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
The singular values (from an SVD; singular value decomposition) equal the diagonal elements of a diagonal matrix.
To demonstrate this, create a 5x8 matrix in which the diagonal elements are defined as the row indices squared. Then, extract the singular values using numpy’s linalg module, and print out the matrix and its singular values:
[[ 1. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 4. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 9. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 16. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 25. 0. 0. 0.]]
[25. 16. 9. 4. 1.].
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
.
.
.
.
import numpy as np
m,n = 5,8
D = np.zeros((m,n))
for i in range(m):
D[i,i] = (i+1)**2
print(D,’\n’)
print(np.linalg.svd(D)[1])


Hello,
Here's my solution:
# DDC-50: Singular values of a diagonal matrix
import numpy as np
mat = np.zeros((5,8))
for i in range (0,5):
for j in range (0,5):
if i == j:
mat [i,j] = (i+1)**2
print (mat)
U, s, Vh = np.linalg.svd (mat)
print (s)