'Singular Value Decomposition (SVD) outputs a 1-D singular value array, instead of 2-D diagonal matrix [Python]

I was posting a question on similar subject, and encountered another more important question.

When I apply SVD to a matrix 'A' (code below) the output I get is the expected 2-D eigenvector matrices ('U' and 'V') and an unexpected 1-D singular value array 'S'.

U,S,V=np.linalg.svd(A)

For context: The reason for it being unexpected is that Singular Value Decomposition should result in the product of three matrices. The middle matrix (in this case 1-D array) should be a diagonal matrix, holding non-negative singular values in decreasing order of magnitude.

Why does Python 'transform' the matrix into an array? Is there a way around it?

Thanks!



Solution 1:[1]

This is made quite clear in the docs, there you'll see that:

s : (…, K) array: Vector(s) with the singular values, within each vector sorted in descending order. The first a.ndim - 2 dimensions have the same size as those of the input a.

So basically S is just the diagonal of the matrix you mention, i.e the singular values. You can construct a diagonal matrix from it with:

np.diag(S)

Solution 2:[2]

Use np.diag (https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html)

>>> np.diag([0, 4, 8])
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yatu
Solution 2 ev-br