Skip to content

Instantly share code, notes, and snippets.

@warmspringwinds
Last active June 26, 2016 22:19
Show Gist options
  • Save warmspringwinds/22893c1e08f4aef6024d to your computer and use it in GitHub Desktop.
Save warmspringwinds/22893c1e08f4aef6024d to your computer and use it in GitHub Desktop.
Python/Numpy SVD
import numpy as np
input = np.zeros((2, 2), dtype=complex)
input[0, 0] = 0.5 + 250j
input[0, 1] = -0.5
input[1, 0] = 0.5
input[1, 1] = -0.5 + 250j
result = np.linalg.svd(input, full_matrices=True)
# In the output we get three matrices, using which we can reconstruct original matrix.
# M = U*Sigma*V. M - original matrix.
# U: 2 by 2 matrix.
print result[0]
# Output:
# [
# [-0.00141421 -7.07105367e-01j 0.00141421 +7.07105367e-01j]
# [-0.70710678 -1.85770845e-17j -0.70710678 -1.83443295e-17j]
# ]
# Sigma: 2 by 2 diagonal matrix. Only the diagonal elements are displayed. Others are zeros.
print result[1]
# Output:
# [ 250.5005 249.5005]
# V: 2 by 2 matrix.
print result[2]
# Output:
# [
# [-0.70710678+0.j 0.00141421-0.70710537j]
# [ 0.70710678+0.j 0.00141421-0.70710537j]
# ]
# Check for correctness
U = result[0]
V = result[2]
# Cast to Complex data type
s = result[1]
S = np.zeros((2, 2), dtype=complex)
S[:2, :2] = np.diag(s)
# Check the original matrix and the reconstruction.
print np.allclose(input, np.dot(U, np.dot(S, V)))
# Output: True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment