2. 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. Please submit your response in an R Markdown document using our class naming convention, E.g. LFulton_Assignment2_PS2.png You don’t have to worry about permuting rows of A and you can assume that A is less than 5x5, if you need to hard-code any variables in your code. If you doing the entire assignment in R, then please submit only one markdown document for both the problems.

LU = function(A){
  
  # Get matrix dimensions
  
  rows <- columns <- dim(A)[1]
  
  # A = LDU
  # L = Lower triangle matrix 
  # D = Diagonal matrix 
  # U = Upper triangle matrix 
  
  U <- A
  L <- D <-  diag(rows)
 
  #Column Loop
  for (j in 1:(columns-1)){
    #row loop
    for (i in (j+1):rows){
      #elimination
      L[i,j] <- (U[i,j]/U[j,j])
      U[i,] <- U[i,]-(U[j,]*L[i,j])
    }
  }
  #transfer the middle diagonal from upper triangular matrix
  diag(D) <- diag(U)
  for (l in 1:rows){
    U[l,] <- U[l,]/U[l,l]
  }
  
  LDU = list("Lower"=L,"Diagonal"=D,"Upper"=U)
return(LDU)
  
}
#Matrix example
A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), nrow=3, ncol=3)

LU(A)
## $Lower
##      [,1]      [,2] [,3]
## [1,]    1 0.0000000    0
## [2,]    1 1.0000000    0
## [3,]    3 0.3333333    1
## 
## $Diagonal
##      [,1] [,2]     [,3]
## [1,]    1    0 0.000000
## [2,]    0   -3 0.000000
## [3,]    0    0 7.333333
## 
## $Upper
##      [,1] [,2]       [,3]
## [1,]    1    2 -1.0000000
## [2,]    0    1  0.3333333
## [3,]    0    0  1.0000000