Monday, 28 March 2016

Characteristic polynomials

In R, we can obtain the characteristic polynomial for a symmetric matrix (such as the adjacency matrices of undirected graphs: see previous posts) using the pracma::charpoly function. This returns the coefficients of the polynomial det(xI - A) in decreasing powers of x.

library(pracma)
library(igraph)
library(Matrix)

# Characteristic polynomial of the 3x3 identity matrix:
diag(c(1,1,1))
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    1    0
# [3,]    0    0    1

charpoly(diag(c(1,1,1)))
[1]  1 -3  3 -1

# x^3 -3x^2 +3x -1

# adjacency matrix for the Petersen graph:
pet <- get.adjacency(make_graph('petersen'))

pet
#10 x 10 sparse Matrix of class "dgCMatrix"
#                         
# [1,] . 1 . . 1 1 . . . .
# [2,] 1 . 1 . . . 1 . . .
# [3,] . 1 . 1 . . . 1 . .
# [4,] . . 1 . 1 . . . 1 .
# [5,] 1 . . 1 . . . . . 1
# [6,] 1 . . . . . . 1 1 .
# [7,] . 1 . . . . . . 1 1
# [8,] . . 1 . . 1 . . . 1
# [9,] . . . 1 . 1 1 . . .
#[10,] . . . . 1 . 1 1 . .

charpoly(pet)
# Error: is.numeric(a) is not TRUE

igraph adjacency matrices are of 'Matrix' class and can't be used directly in charpoly (which expects base R numeric matrices as input). We define a function to return the coefficients of the characteristic polynomial for a graph, or a 'Matrix' or a matrix:

Charpoly <- function(graph.or.matrix){
  require(pracma)
  require(igraph)
  require(Matrix)
  if(is(graph.or.matrix, 'igraph')){
    return(Charpoly(get.adjacency(graph.or.matrix)))
    }
  if(is(graph.or.matrix, 'Matrix')){
    return(Charpoly(as.matrix(graph.or.matrix)))
    }
  charpoly(graph.or.matrix)
  }

Charpoly(make_graph('petersen'))
 [1]    1    0  -15    0   75  -24 -165  120  120 -160   48
That is, the characteristic polynomial is 
x^10 - 15x^8 + 75x^6 -24x^5 ....

Charpoly(pet)
 [1]    1    0  -15    0   75  -24 -165  120  120 -160   48



No comments:

Post a Comment