Cofactor Matrices
Matlab, 42 33 bytes
Using an anonymous function:
@(A)round(inv(A+eps)'*det(A+eps))
Input and output are matrices (2D numeric arrays).
eps
is added in case the matrix is singular. It is "removed" using round
(the true result is guaranteed to be an integer).
Example:
>> @(A)round(inv(A+eps)'*det(A+eps))
ans =
@(A)round(inv(A+eps)'*det(A+eps))
>> ans([-3,2,-5; -1,0,-2; 3,-4,1])
ans =
-8 -5 4
18 12 -6
-4 -1 2
Example with singular matrix:
>> @(A)round(inv(A+eps)'*det(A+eps))
ans =
@(A)round(inv(A+eps)*det(A+eps)')
>> ans([1,0 ; 0,0])
ans =
0 0
0 1
Or try it online in Octave.
Mathematica, 27 35 bytes
Thread[Det[#+x]Inverse[#+x]]/.x->0&
R, 121 94 bytes
function(A)t(outer(1:(n=NROW(A)),1:n,Vectorize(function(i,j)(-1)^(i+j)*det(A[-i,-j,drop=F]))))
This is an absurdly long function that accepts an object of class matrix
and returns another such object. To call it, assign it to a variable.
Ungolfed:
cofactor <- function(A) {
# Get the number of rows (and columns, since A is guaranteed to
# be square) of the input matrix A
n <- NROW(A)
# Define a function that accepts two indices i,j and returns the
# i,j cofactor
C <- function(i, j) {
# Since R loves to drop things into lower dimensions whenever
# possible, ensure that the minor obtained by column deletion
# is still a matrix object by adding the drop = FALSE option
a <- A[-i, -j, drop = FALSE]
(-1)^(i+j) * det(a)
}
# Obtain the adjugate matrix by vectorizing the function C over
# the indices of A
adj <- outer(1:n, 1:n, Vectorize(C))
# Transpose to obtain the cofactor matrix
t(adj)
}