問題描述
R 高斯消除和 qr 分解 (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:
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
.
(by user1539634、Bhas)