A <- matrix(c(1,-1,2,-0,3,4),ncol=3)
X <- A%*%t(A)
Y <- t(A)%*%(A)y_eigen <- eigen(Y)
x_eigen <- eigen(X)
round(y_eigen$values,3)## [1] 26.602 4.398 0.000
round(x_eigen$values,3)## [1] 26.602 4.398
svd(A)## $d
## [1] 5.157693 2.097188
##
## $u
## [,1] [,2]
## [1,] -0.6576043 -0.7533635
## [2,] -0.7533635 0.6576043
##
## $v
## [,1] [,2]
## [1,] 0.01856629 -0.6727903
## [2,] -0.25499937 -0.7184510
## [3,] -0.96676296 0.1765824
sing_val_x <- svd(A)$d
round(sing_val_x,3)==round(sqrt(x_eigen$values),3)## [1] TRUE TRUE
my_svd <- svd(A)
x_eigen$vectors==my_svd$u## [,1] [,2]
## [1,] FALSE TRUE
## [2,] FALSE TRUE
my_svd$u[,1] <- my_svd$u[,1]*-1
round(x_eigen$vectors,3)==round(my_svd$u,3)## [,1] [,2]
## [1,] TRUE TRUE
## [2,] TRUE TRUE
To find the inverse of matrix A
\[A^{-1} = 1/det(A)*adj(A)\]
To find the adjunct of matrix A \[adj(A) =[C_{row,col}]^t \]
The cofactor matrix is the results of \[ [C_{row,col}]=-1^{row+col} * det (Minor_{row,col}) \]
look at each row and column of oriignal matrix and calculate the cofactor matrix by performing the operation above \[ [C_{row,col}]=-1^{row+col} * det (Minor_{row,col}) \]
This step is done outside of the matrix,
get_inverse <- function(matrix){
if (det(matrix)== 0) {
print("matrix is not invertible")
}
## get matrix size
rows <- dim(matrix)[1]
co_factor_matrix <- matrix(0,rows,ncol=rows)
## augment co_factor matrix by using adjugate formula
for (row in (1:rows)) {
for (col in (1:rows)){
co_factor_matrix[row,col] <- (-1)^(row+col)* det(matrix[-row,-col],ncol=rows-1)
}
}
returned_matrix <- (1/det(matrix))*t(co_factor_matrix)
return(returned_matrix)
}mat_A <- matrix(c(1,0,1,2,4,0,3,5,6),ncol=3)
round(get_inverse(mat_A),3)==round(solve(mat_A),3)## [,1] [,2] [,3]
## [1,] TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE
get_inverse(mat_A)%*%mat_A## [,1] [,2] [,3]
## [1,] 1 -8.881784e-16 -1.332268e-15
## [2,] 0 1.000000e+00 0.000000e+00
## [3,] 0 0.000000e+00 1.000000e+00