Created
December 11, 2017 13:52
-
-
Save codeboy101/eeead888032a29bc325364944b23a178 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def qr_decomposition(A): | |
if A.shape[0] != A.shape[1]: | |
return -1 | |
U = [0 for i in range(A.shape[0])] | |
E = U | |
"""get columns""" | |
columns = [1 for i in range(A.shape[0])] | |
for x in range(A.shape[1]): | |
columns[x] = np.array([A[i][x] for i in range(A.shape[0])]).reshape(A.shape[0], 1) | |
""" use gram schmidt """ | |
for i in range(len(columns)): | |
""" get orthogonal vector """ | |
U[i] = columns[i] - total_projection(columns[i], U, i-1) | |
"""normalize the vector""" | |
E[i] = U[i]/norm(U[i]) | |
"""construct Q and R""" | |
Q = np.array([i for i in E]).reshape(3,3).T | |
R = np.matmul(Q.T, A) | |
return Q, R | |
def compute_projection(a, u): | |
inner_products = np.dot(a.T, u)/np.dot(u.T, u) | |
return u * inner_products | |
def total_projection(a, U, k): | |
total = 0 | |
for x in range(k+1): | |
total += compute_projection(a, U[x]) | |
return total | |
def norm(v): | |
return np.power(np.sum(np.power(v, 2)), 1/2) | |
A = np.array([12, -51, 4, 6, 167, -68, -4, 24, -41]).reshape(3,3) | |
matrices = qr_decomposition(A) | |
print(matrices) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment