在R中得到伴随矩阵

Ins*_*ang 3 r

矩阵的第(i,j)个次要是删除了第i行和第j列的矩阵.

minor <- function(A, i, j)
{
  A[-i, -j]  
}
Run Code Online (Sandbox Code Playgroud)

第(i,j)个辅助因子是功率i + j的第(i,j)个次要时间-1.

cofactor <- function(A, i, j)
{
  -1 ^ (i + j) * minor(A, i, j)
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我得到了A的辅助因子,那我怎么能得到伴随矩阵?

Vin*_*ynd 6

你需要括号括号-1次要定义中的决定因素.

之后,你可以使用循环或 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)
Run Code Online (Sandbox Code Playgroud)