2013-05-26 108 views
3

矩陣的第(i,j)次微調是移除了第i行和第j列的矩陣。第(i,j)個輔因子是第(i,j)次冪-1次方i + j的第(i,j)次。獲取R中的伴隨矩陣

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

通過這種方式,我得到了A的輔因子,那麼我怎樣才能得到伴隨矩陣?

+0

通過伴隨你的意思是共軛轉? –

回答

6

您需要圍繞-1 的圓括號和minor的定義中的決定因素。

之後,你可以使用一個循環或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)