Problem set 2

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)
## Warning: package 'matrixcalc' was built under R version 4.0.3
LDU <- function(A) {
 
 if(is.square.matrix(A) == FALSE) {
    return("not a square matrix!")
  }
  
  U <- A
  D <- dim(A)[1]
  L <- diag(D)
  
  
  if (D==1) {
    return(list(L,U))
  }
  
  
  for(i in 2:D) {
    for(j in 1:(i-1)) {
      mlt <- -U[i,j] / U[j,j]
      U[i, ] <- mlt * U[j, ] + U[i, ]
      L[i,j] <- -mlt
    }
  }
  return(list(L,U))
}


test<- matrix(c(2, 2, 8,4,9,9, 2, 0, 1),nrow=3)
LDU(test)
## [[1]]
##      [,1] [,2] [,3]
## [1,]    1  0.0    0
## [2,]    1  1.0    0
## [3,]    4 -1.4    1
## 
## [[2]]
##      [,1] [,2] [,3]
## [1,]    2    4  2.0
## [2,]    0    5 -2.0
## [3,]    0    0 -9.8