Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Gaussian Elimination and qr factorization

I found the following R code using qr factorization cannot recover the original matrix. I cannot figure out why.

a <- matrix(runif(180),ncol=6)
a[,c(2,4)] <- 0
b <- qr(a)
d <- qr.Q(b) %*% qr.R(b)

then d is different from a in the way that all the zero columns are moved the the right side. It seems that qr factorization does not keep the row space.


1 Answers

When you read the help for qr you see that R uses a pivoted QR-decomposition. So

str(b) 

gives

List of 4
 $ qr   : num [1:30, 1:6] -3.2292 0.218 0.0623 0.0371 0.302 ...
 $ rank : int 4
 $ qraux: num [1:6] 1.05 1.11 1.04 1.22 0 ...
 $ pivot: int [1:6] 1 3 5 6 2 4
 - attr(*, "class")= chr "qr"

Thus you need to apply pivot to a or the inverse of pivot to d to line the matrices up correctly. So

pivots <- b$pivot
d.ok <- d[,order(pivots)]
all.equal(a,d.ok)

gives

[1] TRUE

You can also do

a.p <- a[,pivots]
all.equal(a.p,d)

which also results in TRUE.

like image 81
Bhas Avatar answered Dec 19 '25 13:12

Bhas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!