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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With