## Add one column
## generate sample data
set.seed(1234)
n <- 12
p <- 5
X <- matrix(rnorm(n * p, 1), n, p)
## get the initial QR factorization
output <- qr(X, complete = TRUE)
Q <- output$Q
R <- output$R
## create column u to be added
k <- p+1
u <- matrix(rnorm(n), n, 1)
X1 <- cbind(X, u)
## update the QR decomposition
out <- fastQR::qrupdate(Q = Q, R = R,
k = k, U = u,
type = "column",
fast = FALSE,
complete = TRUE)
## check
round(out$Q %*% out$R - X1, 5)
max(abs(out$Q %*% out$R - X1))
## Add m columns
## create data: n > p
set.seed(1234)
n <- 10
p <- 5
X <- matrix(rnorm(n * p, 1), n, p)
## get the initial QR factorization
output <- fastQR::qr(X, complete = TRUE)
Q <- output$Q
R <- output$R
## create the matrix of two columns to be added
## in position 2
k <- 2
m <- 2
U <- matrix(rnorm(n*m), n, m)
X1 <- cbind(X[,1:(k-1)], U, X[,k:p])
# update the QR decomposition
out <- fastQR::qrupdate(Q = Q, R = R,
k = k, U = U, type = "column",
fast = FALSE, complete = TRUE)
## check
round(out$Q %*% out$R - X1, 5)
max(abs(out$Q %*% out$R - X1))
## Add one row
## create data: n > p
set.seed(1234)
n <- 12
p <- 5
X <- matrix(rnorm(n * p, 1), n, p)
## get the initial QR factorization
output <- fastQR::qr(X, complete = TRUE)
Q <- output$Q
R <- output$R
R1 <- R[1:p,]
## create the row u to be added
u <- matrix(data = rnorm(p), p, 1)
k <- n+1
if (k<=n) {
X1 <- rbind(rbind(X[1:(k-1), ], t(u)), X[k:n, ])
} else {
X1 <- rbind(rbind(X, t(u)))
}
## update the QR decomposition
out <- fastQR::qrupdate(Q = Q, R = R,
k = k, U = u,
type = "row",
complete = TRUE)
## check
round(out$Q %*% out$R - X1, 5)
max(abs(out$Q %*% out$R - X1))
## Add m rows
## create data: n > p
set.seed(1234)
n <- 12
p <- 5
X <- matrix(rnorm(n * p, 1), n, p)
## get the initial QR factorization
output <- fastQR::qr(X, complete = TRUE)
Q <- output$Q
R <- output$R
R1 <- R[1:p,]
## create the matrix of rows U to be added:
## two rows in position 5
m <- 2
U <- matrix(data = rnorm(p*m), p, m)
k <- 5
if (k<=n) {
X1 <- rbind(rbind(X[1:(k-1), ], t(U)), X[k:n, ])
} else {
X1 <- rbind(rbind(X, t(U)))
}
## update the QR decomposition
out <- fastQR::qrupdate(Q = Q, R = R,
k = k, U = U,
type = "row",
complete = FALSE)
## check
round(out$Q %*% out$R - X1, 5)
max(abs(out$Q %*% out$R - X1))
Run the code above in your browser using DataLab