Matrix factorization is a very important problem. There are supercomputers built just to do matrix factorizations. Every second you are on an airplane, matrices are being factorized. Radars that track flights use a technique called Kalman filtering. At the heart of Kalman Filtering is a Matrix Factorization operation. Kalman Filters are solving linear systems of equations when they track your flight using radars. Write an R function to factorize a square matrix A into LU or LDU, whichever you prefer.
library(matrixcalc)
library(Matrix)
## Warning: package 'Matrix' was built under R version 3.5.3
fctR <- function(A){
n <- nrow(A) #number of rows in A
U <- A
L <- diag(n) #assign diagonal to L
for (j in c(1:n)){
for(i in c(2:n)){
if(i > j){
the_row <- U[j,]
multiplier <- U[i, j] / the_row[j]
U[i,] <- U[i,] - (multiplier * the_row)
L[i,j] <- multiplier
}
}
}
return(list(L=L, U=U))
}
A <- matrix(c(2,1,-6,4,-4,-9,-4,3,5),3,3)
A;
## [,1] [,2] [,3]
## [1,] 2 4 -4
## [2,] 1 -4 3
## [3,] -6 -9 5
factors <- fctR(A)
factors$L
## [,1] [,2] [,3]
## [1,] 1.0 0.0 0
## [2,] 0.5 1.0 0
## [3,] -3.0 -0.5 1
factors$U
## [,1] [,2] [,3]
## [1,] 2 4 -4.0
## [2,] 0 -6 5.0
## [3,] 0 0 -4.5
luA <- lu.decomposition(A)
luA$L
## [,1] [,2] [,3]
## [1,] 1.0 0.0 0
## [2,] 0.5 1.0 0
## [3,] -3.0 -0.5 1
luA$U
## [,1] [,2] [,3]
## [1,] 2 4 -4.0
## [2,] 0 -6 5.0
## [3,] 0 0 -4.5