Show that ATA != AAT in general. (Proof and demonstration.)
## creating a 3x3 matrix with numbers 1 through 9
A <- matrix(seq(from= 1, to=9), nrow=3, byrow = T)
A
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
creating the transpose of the first A and multiplying it by A and storing it in a variable
ATA <- t(A) %*% A
ATA
## [,1] [,2] [,3]
## [1,] 66 78 90
## [2,] 78 93 108
## [3,] 90 108 126
multiplying the A by the transpose of A
AAT <-A %*% (t(A))
AAT
## [,1] [,2] [,3]
## [1,] 14 32 50
## [2,] 32 77 122
## [3,] 50 122 194
We can see that they’re not equal but just to make sure lets use a function to check if they’re equal and it returns a Boolean
equal <- all(ATA == AAT)
print(paste('Are the Matrices equivalent?',equal))
## [1] "Are the Matrices equivalent? FALSE"
Conclusion we conclude that ATA != AAT
For a special type of square matrix A, we get AT A = AAT Under what conditions could this be true? To make AT A = AAT, the matrix has to be symmetric, meaning the transpose of the matrix has to be equal to the matrix itself
I <- diag(3)
# Print the identity matrix
print("Identity matrix:")
## [1] "Identity matrix:"
print(I)
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
if (all(I %*% t(I) == t(I) %*% I)) {
print("AT A = A AT")
} else {
print("AT A != A AT")
}
## [1] "AT A = A AT"
Write an R function to factorize a square matrix A into LU or LDU, whichever you prefer.
LU_factorization <- function(B) {
n <- nrow(B)
L <- matrix(0, nrow = n, ncol = n)
U <- matrix(0, nrow = n, ncol = n)
for (j in 1:n) {
U[1, j] <- B[1, j]
}
for (i in 1:n) {
L[i, i] <- 1
}
for (i in 2:n) {
L[i, 1] <- B[i, 1] / U[1, 1]
}
for (i in 2:n) {
for (j in 2:n) {
if (j >= i) {
U[i, j] <- B[i, j] - sum(L[i, 1:(i-1)] * U[1:(i-1), j])
} else {
L[j, i] <- (B[j, i] - sum(L[j, 1:(j-1)] * U[1:(j-1), i])) / U[j, j]
}
}
}
return(list(L = L, U = U))
}
B <- matrix(c(2, -1, -2, -4, 6, 3, -4, 1, 10), nrow = 3, byrow = TRUE)
# Factorize B into LU decomposition
LU <- LU_factorization(B)
L <- LU$L
U <- LU$U
print("Lower triangular matrix L:")
## [1] "Lower triangular matrix L:"
print(L)
## [,1] [,2] [,3]
## [1,] 1 0 0.00
## [2,] -2 1 -0.25
## [3,] -2 0 1.00
print("Upper triangular matrix U:")
## [1] "Upper triangular matrix U:"
print(U)
## [,1] [,2] [,3]
## [1,] 2 -1 -2
## [2,] 0 4 -1
## [3,] 0 0 6