Defining LU Factorization Function Logic
LU_fact <- function(A) {
UM <- A # Initial upper triangular matrix
n <- dim(A)[1] # counter of number of rows in the matrix to loop through
LM <- diag(n) # Identity matrix as an initial lower triangular matrix
## Get and loop through multipliers (E21, E31, E32,..., etc.) to calculate the UpperM and apply the inverse for the LowerM
for(i in 2:n) {
for(j in 1:(i-1)) {
mult <- -UM[i,j]
UM[i, ] <- mult * UM[j, ] + UM[i, ]
LM[i,j] <- -mult
}
}
return(list(LM,UM))
}
Testing LU Factorization Function
A <- matrix(c(1,-2,3,3,2,1,4,5,6), nrow=3, ncol=3, byrow=TRUE)
## A <- matrix(c(1,2,3,1), nrow=2, ncol=2, byrow=TRUE)
A_LU <- LU_fact(A)
LM <- A_LU[[1]]
UM <- A_LU[[2]]
LM
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 3 1 0
## [3,] 4 13 1
## [,1] [,2] [,3]
## [1,] 1 -2 3
## [2,] 0 8 -8
## [3,] 0 -91 98
## [,1] [,2] [,3]
## [1,] 1 -2 3
## [2,] 3 2 1
## [3,] 4 5 6
## [,1] [,2] [,3]
## [1,] 1 -2 3
## [2,] 3 2 1
## [3,] 4 5 6
## [,1] [,2] [,3]
## [1,] TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE