The QR factorization can be used to solve linear least squares problems. The QR factorization decomposes an m x n matrix A (with m≥n) into two matrices called Q and R, such that A=QR. Q is an m x n matrix with orthonormal columns and R is an n x n matrix that is upper triangular and invertible. In this example, we will see how easy it is to compute the QR factorization with Sage.
# This is an example where it's important to specify the correct ring A = Matrix(RDF, [[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]]) print("Matrix A:") show(A) Q, R = A.QR() print("Matrix with orthonormal basis:") show(Q) print("Upper diagonal matrix:") show(R) print("Q*R recovers A:") show(Q*R)
The output should look like this: