NumPy's `linalg.svd` function computes the SVD.
import numpy as np
# Define a matrix (can be non-square)
A = np.array([[1, 2, 3],
[4, 5, 6]])
print("Matrix A:\n", A)
# Compute SVD
# full_matrices=False for economy SVD
U, s_diag, Vh = np.linalg.svd(A, full_matrices=False)
print("\nU (left-singular vectors):\n", U)
print("\ns_diag (singular values as a 1D array):\n", s_diag)
print("\nVh (V transpose, right-singular vectors as rows):\n", Vh)
# To reconstruct A, Sigma needs to be formed into a diagonal matrix
# For economy SVD where m >= n (as in this A is 2x3, so m < n), Sigma will be m x n
# If A is m x n, U is m x k, Sigma is k x k (diag(s_diag)), Vh is k x n, where k = min(m,n)
Sigma = np.zeros((A.shape[0], A.shape[1]))
# Populate Sigma with singular values
# For A (2x3), U (2x2), s_diag (2,), Vh (2x3). Sigma should be 2x2 to make U @ Sigma work, then result @ Vh
# Or, more generally, Sigma_reconstruct is min(m,n) x min(m,n)
# A_reconstructed = U @ np.diag(s_diag) @ Vh # This is common if U,s,Vh are from full_matrices=False and m>=n or specific economy handling
# Constructing Sigma matrix for A_reconstructed = U @ Sigma_full @ Vh_full_V
# For A = U S V^T, if U is (m,k), S must be (k,k) (from s_diag), V^T is (k,n)
Sigma_matrix = np.diag(s_diag) # This will be k x k where k = min(m,n)
# If m < n, U is m x m, Sigma_matrix from np.diag(s_diag) is m x m. We need to pad Sigma or use U[:,:m] if m!=k
# A (2x3), U(2x2), s_diag(2), Vh(2x3)
# Sigma_matrix from np.diag(s_diag) = [[s1,0],[0,s2]] (2x2)
A_reconstructed = U @ Sigma_matrix @ Vh
print("\nReconstructed A from U @ diag(s) @ Vh:\n", A_reconstructed)
print("Original A and Reconstructed A are close:", np.allclose(A, A_reconstructed))