Skip to content

Instantly share code, notes, and snippets.

@drewdaemon
Created December 30, 2017 17:27
Show Gist options
  • Save drewdaemon/4e8e5da96043fe93e70425da05f8a49f to your computer and use it in GitHub Desktop.
Save drewdaemon/4e8e5da96043fe93e70425da05f8a49f to your computer and use it in GitHub Desktop.
def qr_gram_schmidt(A):
"""Compute the reduced QR decomposition of A via Modified Gram-Schmidt.
Parameters:
A ((m,n) ndarray): A matrix of rank n.
Returns:
Q ((m,n) ndarray): An orthonormal matrix.
R ((n,n) ndarray): An upper triangular matrix.
"""
m, n = A.shape
Q = A.copy()
R = np.zeros((n, n))
for i in range(n):
R[i, i] = la.norm(Q[:, i])
Q[:, i] = Q[:, i]/R[i, i]
for j in range(i + 1, n):
R[i, j] = Q[:, j] @ Q[:, i]
Q[:, j] = Q[:, j] - R[i, j] * Q[:,i]
return Q, R
@drewdaemon
Copy link
Author

When A =
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])

Scipy's output:
array([[ 0. , -0.83666003, 0.53970407, 0.09337836],
[-0.26726124, -0.47809144, -0.78920555, 0.27776718],
[-0.53452248, -0.11952286, -0.04070111, -0.83566944],
[-0.80178373, 0.23904572, 0.29020259, 0.4645239 ]]),

My output:
array([[ 0. , 0.83666003, 0. , 0.86999932],
[ 0.26726124, 0.47809144, -0.33333333, 0.41083301],
[ 0.53452248, 0.11952286, -0.66666667, 0.06041662],
[ 0.80178373, -0.23904572, -0.66666667, -0.26583313]]),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment