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

Viewed 820

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!

2 Answers

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)
Related