Search code examples
reigenvectoreigenvaluelinear-equation

A function for calculating the eigenvalues of a matrix in R


I want to write a function like eigen() to calculating eigenvalues and eigenvectors of an arbitary matrix. I wrote the following codes for calculation of eigenvalues and I need a function or method to solve the resulted linear equation.

eig <- function(x){
       if(nrow(x)!=ncol(x)) stop("dimension error")
          ff <- function(lambda){
                for(i in 1:nrow(x)) x[i,i] <- x[i,i] - lambda
                }
det(x)
}

I need to solve det(x)=0 that is a polynomial linear equation to find the values of lambda. Is there any way?


Solution

  • Here is one solution using uniroot.all:

    library(rootSolve)
    myeig <- function(mat){
      myeig1 <- function(lambda) {
        y = mat
        diag(y) = diag(mat) - lambda
        return(det(y))
      }
    
      myeig2 <- function(lambda){
        sapply(lambda, myeig1)
      }
      uniroot.all(myeig2, c(-10, 10))
    }
    
    R > x <- matrix(rnorm(9), 3)
    R > eigen(x)$values
    [1] -1.77461906 -1.21589769 -0.01010515
    R > myeig(x)
    [1] -1.77462211 -1.21589767 -0.01009019