9

I am using Python with numpy to do linear algebra.

I performed numpy SVD on a matrix to get the matrices U,i, and V. However the i matrix is expressed as a 1x4 matrix with 1 row. i.e.: [ 12.22151125 4.92815942 2.06380839 0.29766152].

How can I get numpy to express the i matrix as a diagonal matrix like so: [[12.22151125, 0, 0, 0],[0,4.92815942, 0, 0],[0,0,2.06380839,0 ],[0,0,0,0.29766152]]

Code I am using:

A = np.matrix([[3, 4, 3, 1],[1,3,2,6],[2,4,1,5],[3,3,5,2]])

U, i, V = np.linalg.svd(A,full_matrices=True)

So I want i to be a full diagonal matrix. How an I do this?

2 Answers 2

12

Use numpy's diag function:

numpy.diag(i)

From the documentation:

Extract a diagonal or construct a diagonal array.

2
  • huh it's that easy!
    – theGuy05
    Commented Jan 19, 2018 at 20:18
  • 1
    Yes, I find myself using diag surprisingly often. Commented Jan 19, 2018 at 20:27
4

How can I get numpy to express the i matrix as a diagonal matrix like so: [[12.22151125, 0, 0, 0],[0,4.92815942, 0, 0],[0,0,2.06380839,0 ],[0,0,0,0.29766152]]

You should use numpy.diagflat(flatted_input, k=0), to Create a two-dimensional array with the flattened input as a diagonal

example

In [1]: flatted_input = [12, 4, 2, 1]

In [2]: np.diagflat(flatted_input)

Out [2]: array([[12, 0, 0, 0],
                [0, 4, 0, 0],
                [0, 0, 2, 0],
                [0, 0, 0, 1]])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.