Getting the singular values of np.linalg.svd as a matrix

Viewed 4488

Given a 5x4 matrix A =

enter image description here

A piece of python code to construct the matrix

A = np.array([[1, 0, 0, 0],
              [0, 0, 0, 4],
              [0, 3, 0, 0],
              [0, 0, 0, 0],
              [2, 0, 0, 0]])

wolframalpha gives the svd result

enter image description here

the Vector(s) with the singular values Σ is in this form

enter image description here

the equivalent quantity (NumPy call it s) in the output of np.linalg.svd is in this form

[ 4.          3.          2.23606798 -0.        ]

is there a way to have the quantity in output of numpy.linalg.svd shown as wolframalpha?

1 Answers

You can get most of the way there with diag:

>>> u, s, vh = np.linalg.svd(a)
>>> np.diag(s)
array([[ 4.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  3.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  2.23606798,  0.        ],
       [ 0.        ,  0.        ,  0.        , -0.        ]])

Note that wolfram alpha is giving an extra row. Getting that is marginally more involved:

>>> sigma = np.zeros(A.shape, s.dtype)
>>> np.fill_diagonal(sigma, s)
>>> sigma
array([[ 4.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  3.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  2.23606798,  0.        ],
       [ 0.        ,  0.        ,  0.        , -0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ]])

Depending on what your goal is, removing a column from U might be a better approach than adding a row of zeros to sigma. That would look like:

>>> u, s, vh = np.linalg.svd(a, full_matrices=False)
Related