#part1:
# Answer1:
A = matrix(c(1,4,2,7,0,-3,1,3,-2), nrow=3, byrow=TRUE) # matrix A
A
## [,1] [,2] [,3]
## [1,] 1 4 2
## [2,] 7 0 -3
## [3,] 1 3 -2
At = t(A) #transpose of matrix A
At
## [,1] [,2] [,3]
## [1,] 1 7 1
## [2,] 4 0 3
## [3,] 2 -3 -2
A %*% At # multiply matrix A by it transpose
## [,1] [,2] [,3]
## [1,] 21 1 9
## [2,] 1 58 13
## [3,] 9 13 14
At %*% A # do the opposite multiply the matrix transpose by the matrix
## [,1] [,2] [,3]
## [1,] 51 7 -21
## [2,] 7 25 2
## [3,] -21 2 17
A %*% At == At %*% A # comparison , the results is false , which mean A^TA not equal to AA^T
## [,1] [,2] [,3]
## [1,] FALSE FALSE FALSE
## [2,] FALSE FALSE FALSE
## [3,] FALSE FALSE FALSE
#answer2:
A= matrix(c(2,1,0,1,2,0,0,0,2), nrow=3, byrow=TRUE) # try symmetric matrix
A
## [,1] [,2] [,3]
## [1,] 2 1 0
## [2,] 1 2 0
## [3,] 0 0 2
At = t(A) #transpose of matrix A
At
## [,1] [,2] [,3]
## [1,] 2 1 0
## [2,] 1 2 0
## [3,] 0 0 2
A %*% At # multiply matrix A by it transpose
## [,1] [,2] [,3]
## [1,] 5 4 0
## [2,] 4 5 0
## [3,] 0 0 4
At %*% A # do the opposite multiply the matrix transpose by the matrix
## [,1] [,2] [,3]
## [1,] 5 4 0
## [2,] 4 5 0
## [3,] 0 0 4
A %*% At == At %*% A # comparison , the results is true , when the matrix is symmetric A^TA is equal to AA^T
## [,1] [,2] [,3]
## [1,] TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE
#Part2:
factorizeLU <- function(A) {
# see A is square
if (dim(A)[1]!=dim(A)[2]) {
return(NA)
}
U <- A
n <- dim(A)[1]
L <- diag(n)
# If dimension is 1, then U=A and L=[1]
if (n==1) {
return(list(L,U))
}
# Determine the multiplier for each position and add it to L
for(i in 2:n) {
for(j in 1:(i-1)) {
multiplier <- -U[i,j] / U[j,j]
U[i, ] <- multiplier * U[j, ] + U[i, ]
L[i,j] <- -multiplier
}
}
return(list(L,U))
}
# Example
A <- matrix(c(1,2,-3,-2,5,4,7,2,11), nrow=3, byrow=TRUE)
LU <- factorizeLU(A)
L<-LU[[1]]
U<-LU[[2]]
A
## [,1] [,2] [,3]
## [1,] 1 2 -3
## [2,] -2 5 4
## [3,] 7 2 11
L
## [,1] [,2] [,3]
## [1,] 1 0.000000 0
## [2,] -2 1.000000 0
## [3,] 7 -1.333333 1
U
## [,1] [,2] [,3]
## [1,] 1 2 -3.00000
## [2,] 0 9 -2.00000
## [3,] 0 0 29.33333
A == L %*% U
## [,1] [,2] [,3]
## [1,] TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE