knitr::include_graphics('4-1.png')

# Creating matrix A

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
# Transformation

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
# Calculate eigvenvalues and eigenvectors

eigen_X <- eigen(X)
print(eigen_X) # Printing eigenvalues and eigenvectors for X
## eigen() decomposition
## $values
## [1] 26.601802  4.398198
## 
## $vectors
##           [,1]       [,2]
## [1,] 0.6576043 -0.7533635
## [2,] 0.7533635  0.6576043
eigen_Y <- eigen(Y)
print(eigen_Y) # Printing eigenvalues and eigenvectors for Y
## eigen() decomposition
## $values
## [1] 2.660180e+01 4.398198e+00 1.058982e-16
## 
## $vectors
##             [,1]       [,2]       [,3]
## [1,] -0.01856629 -0.6727903  0.7396003
## [2,]  0.25499937 -0.7184510 -0.6471502
## [3,]  0.96676296  0.1765824  0.1849001
# Calculate left-singular, singular and right-singular functions using SVD function

svd_a <- svd(A)


svd_a$u # left-singular 
##            [,1]       [,2]
## [1,] -0.6576043 -0.7533635
## [2,] -0.7533635  0.6576043
svd_a$d # Singular
## [1] 5.157693 2.097188
svd_a$v # Right-singular
##             [,1]       [,2]
## [1,]  0.01856629 -0.6727903
## [2,] -0.25499937 -0.7184510
## [3,] -0.96676296  0.1765824

In above results, we can clearly see that left singular contains eigenvectors of X and right singular contains eigenvectors of Y and hence they are equivalent.

ans <- svd_a$d^2
ans
## [1] 26.601802  4.398198

It’s proved that both X and Y’s eigenvalues are same and thus are square of A

knitr::include_graphics('4-2.png')

# Cretating function to compute inverse 
inv <- function(x) {
  # check if matrix is square
  if(nrow(x) != ncol(x)) { return('takes only squre matrix as input')}
  cofactor_Matrix <- matrix(rep(0,length(x)),ncol=ncol(x))
  for (i in 1:ncol(x)) {
    for (j in 1:nrow(x)) {
      cofactor_Matrix[i,j] <- det(x[-i,-j])*(-1)^(i+j) 
    }
  }
  return(t(cofactor_Matrix)/det(x)) 
}

# Now let's create a random matrix of 3 rows

A <- matrix(c(1,1,0,2,1,1,1,2,1),nrow=3)
A
##      [,1] [,2] [,3]
## [1,]    1    2    1
## [2,]    1    1    2
## [3,]    0    1    1
# Now let's test the create function "inv"
B <- inv(A)
B
##      [,1] [,2] [,3]
## [1,]  0.5  0.5 -1.5
## [2,]  0.5 -0.5  0.5
## [3,] -0.5  0.5  0.5
# Round to see identity matrix (I)
round(A %*% B)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1