Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get adjoint matrix in R

Tags:

r

The (i,j)th minor of a matrix is that matrix with the ith row and the jth column removed.

minor <- function(A, i, j)
{
  A[-i, -j]  
}

The (i,j)th cofactor is the (i,j)th minor times -1 to the power i + j.

cofactor <- function(A, i, j)
{
  -1 ^ (i + j) * minor(A, i, j)
}

by this way, I got cofactor of A then how can i get adjoint matrix?

like image 358
Insung Kang Avatar asked Sep 14 '25 22:09

Insung Kang


1 Answers

You need parentheses around -1 and a determinant in the definition of the minor.

After that, you could use a loop or outer

# Sample data
n <- 5
A <- matrix(rnorm(n*n), n, n)

# Minor and cofactor
minor <- function(A, i, j) det( A[-i,-j] )
cofactor <- function(A, i, j) (-1)^(i+j) * minor(A,i,j)

# With a loop
adjoint1 <- function(A) {
  n <- nrow(A)
  B <- matrix(NA, n, n)
  for( i in 1:n )
    for( j in 1:n )
      B[j,i] <- cofactor(A, i, j)
  B
}

# With `outer`
adjoint2 <- function(A) {
  n <- nrow(A)
  t(outer(1:n, 1:n, Vectorize(
    function(i,j) cofactor(A,i,j)
  )))
}

# Check the result: these should be equal
det(A) * diag(nrow(A))
A %*% adjoint1(A)
A %*% adjoint2(A)
like image 129
Vincent Zoonekynd Avatar answered Sep 17 '25 13:09

Vincent Zoonekynd