araragi_koyomi
araragi_koyomi

Reputation: 15

Having problems using numpy linalg svd

I'm testing svd decomposition with simple matrix

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

but when I use :

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

the output are U whit shape (2,2), D with shape (2,) and V with shape (3,3) the problem is the shape of V, the svd algorithm should return a 2x3 matrix since my original matrix is a 2x3 matrix and i'm geting 2 singular values, but it return a 3x3 matrix, when i take V[:2,:] and make the product:

U.dot(np.diag(D).dot(V[:2,:]))

it returns the original matrix A, what is happening here? thank you for your reading and answers and sorry for the grammar, i'm beginning in english

Upvotes: 1

Views: 2323

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114781

This is explained in the docstring, but it might take a few readings to get it. The boolean parameter full_matrices determines the shape of the returned arrays. In your case, you want full_matrices=False, e.g.:

In [42]: A = np.array([[1, 2, 3], [4, 5, 6]])

In [43]: U, D, V = np.linalg.svd(A, full_matrices=False)

In [44]: U @ np.diag(D) @ V
Out[44]: 
array([[1., 2., 3.],
       [4., 5., 6.]])

Upvotes: 3

Related Questions