(1) Write an R function to factorize a square matrix A into LU or LDU, whichever you prefer.
factorize_square_Matrix <- function(A, diagonalMatrix, index) {
columns = ncol(A)
rows = nrow(A)
if (index >= columns) {
return(list(diagonalMatrix, A))
} else {
for(i in (index+1):rows) {
multiplier <- (-A[i, index] / A[index, index])
diagonalMatrix[i, index] <- round(-multiplier, 2)
A[i, ] <- A[i, ] + (multiplier * A[index, ])
}
print (A)
}
factorize_square_Matrix(A, diagonalMatrix, index + 1)
}
A <- matrix(c(2, 4, -4, 1, -4, 3, -6, -9, 5), nrow=3, ncol=3, byrow = TRUE)
lowerMatrix <- factorize_square_Matrix(A, diag(nrow(A)), 1)
## [,1] [,2] [,3]
## [1,] 2 4 -4
## [2,] 0 -6 5
## [3,] 0 3 -7
## [,1] [,2] [,3]
## [1,] 2 4 -4.0
## [2,] 0 -6 5.0
## [3,] 0 0 -4.5
L<- lowerMatrix[[1]]
U <- lowerMatrix[[2]]
A == L %*% U
## [,1] [,2] [,3]
## [1,] TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE