A = matrix(c(1,-1,2,0,3,4),nrow=2,ncol=3)
A
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] -1 0 4
X = A %*% t(A)
X
## [,1] [,2]
## [1,] 14 11
## [2,] 11 17
Y = t(A) %*% A
Y
## [,1] [,2] [,3]
## [1,] 2 2 -1
## [2,] 2 4 6
## [3,] -1 6 25
eX = eigen(X)
print(list('Eigen values',eX$values,'Eigen vectors',eX$vectors))
## [[1]]
## [1] "Eigen values"
##
## [[2]]
## [1] 26.601802 4.398198
##
## [[3]]
## [1] "Eigen vectors"
##
## [[4]]
## [,1] [,2]
## [1,] 0.6576043 -0.7533635
## [2,] 0.7533635 0.6576043
eY = eigen(Y)
print(list('Eigen values',eY$values,'Eigen vectors',eY$vectors))
## [[1]]
## [1] "Eigen values"
##
## [[2]]
## [1] 2.660180e+01 4.398198e+00 1.058982e-16
##
## [[3]]
## [1] "Eigen vectors"
##
## [[4]]
## [,1] [,2] [,3]
## [1,] -0.01856629 -0.6727903 0.7396003
## [2,] 0.25499937 -0.7184510 -0.6471502
## [3,] 0.96676296 0.1765824 0.1849001
decomposedA = svd(A)
#u,v,d
print(c(list(decomposedA$u,decomposedA$v,decomposedA$d)))
## [[1]]
## [,1] [,2]
## [1,] -0.6576043 -0.7533635
## [2,] -0.7533635 0.6576043
##
## [[2]]
## [,1] [,2]
## [1,] 0.01856629 -0.6727903
## [2,] -0.25499937 -0.7184510
## [3,] -0.96676296 0.1765824
##
## [[3]]
## [1] 5.157693 2.097188
Eigenvectors of X are the left-singular matrix (u) of A.
Eigenvectors of Y are the right-singular matrix (v) of A.
#Square of non-singular values of A and the eigen values of X
list(decomposedA$d*decomposedA$d,eX$values)
## [[1]]
## [1] 26.601802 4.398198
##
## [[2]]
## [1] 26.601802 4.398198
myInverse = function(A){
#Check if square
if(dim(A)[1] != dim(A)[2]){ return('ERROR : Matrix is not square') }
#Check if determinant is 0
if(det(A) == 0){ return('ERROR : Matrix is singular') }
#Create co-factor matrix
coMatrix = A * 0
#Cofactoring proceedure
for (i in 1:ncol(A)) {
for (j in 1:nrow(A)) {
coMatrix[i,j] = det(A[-i,-j]) * (-1)^(i+j)
}}
inversed = t((coMatrix)/det(A))
return(inversed)
}
A = matrix(c(1,2,4,3,4,3,3,1,1,3,1,8,2,1,7,1),nrow=4)
B = myInverse(A)
C = solve(A)
round(B,4)==round(C,4)
## [,1] [,2] [,3] [,4]
## [1,] TRUE TRUE TRUE TRUE
## [2,] TRUE TRUE TRUE TRUE
## [3,] TRUE TRUE TRUE TRUE
## [4,] TRUE TRUE TRUE TRUE