Skip to contents

QR computes the QR decomposition of a matrix, \(X\), that is an orthonormal matrix, \(Q\) and an upper triangular matrix, \(R\), such that \(X = Q R\).

Usage

QR(X, tol = sqrt(.Machine$double.eps))

Arguments

X

a numeric matrix

tol

tolerance for detecting linear dependencies in the columns of X

Value

a list of three elements, consisting of an orthonormal matrix Q, an upper triangular matrix R, and the rank of the matrix X

Details

The QR decomposition plays an important role in many statistical techniques. In particular it can be used to solve the equation \(Ax = b\) for given matrix \(A\) and vector \(b\). The function is included here simply to show the algorithm of Gram-Schmidt orthogonalization. The standard qr function is faster and more accurate.

See also

Author

John Fox and Georges Monette

Examples

A <- matrix(c(1,2,3,4,5,6,7,8,10), 3, 3) # a square nonsingular matrix
res <- QR(A)
res
#> $Q
#>            [,1]       [,2]       [,3]
#> [1,] -0.2672612 -0.8728716 -0.4082483
#> [2,] -0.5345225 -0.2182179  0.8164966
#> [3,] -0.8017837  0.4364358 -0.4082483
#> 
#> $R
#>           [,1]      [,2]        [,3]
#> [1,] -3.741657 -8.552360 -14.1648458
#> [2,]  0.000000 -1.963961  -3.4914862
#> [3,]  0.000000  0.000000  -0.4082483
#> 
#> $rank
#> [1] 3
#> 
q <- res$Q
zapsmall( t(q) %*% q)   # check that q' q = I
#>      [,1] [,2] [,3]
#> [1,]    1    0    0
#> [2,]    0    1    0
#> [3,]    0    0    1
r <- res$R
q %*% r                 # check that q r = A
#>      [,1] [,2] [,3]
#> [1,]    1    4    7
#> [2,]    2    5    8
#> [3,]    3    6   10

# relation to determinant: det(A) = prod(diag(R))
det(A)
#> [1] -3
prod(diag(r))
#> [1] -3

B <- matrix(1:9, 3, 3) # a singular matrix
QR(B)
#> $Q
#>            [,1]       [,2] [,3]
#> [1,] -0.2672612 -0.8728716    0
#> [2,] -0.5345225 -0.2182179    0
#> [3,] -0.8017837  0.4364358    0
#> 
#> $R
#>           [,1]      [,2]       [,3]
#> [1,] -3.741657 -8.552360 -13.363062
#> [2,]  0.000000 -1.963961  -3.927922
#> [3,]  0.000000  0.000000   0.000000
#> 
#> $rank
#> [1] 2
#>