Data 605 - Discussion DM.C24

Heather Geiger

Start with a 3x3 matrix.

mymatrix <- as.matrix(data.frame(a = c(-2,-4,2), b = c(3,-2,4), c = c(-2,1,2)))

mymatrix
##       a  b  c
## [1,] -2  3 -2
## [2,] -4 -2  1
## [3,]  2  4  2

Multiply the appropriate cells in original matrix by -1 to get cofactors.

cofactors <- mymatrix

cofactors[1,2] = -1*cofactors[1,2]
cofactors[2,1] = -1*cofactors[2,1]
cofactors[2,3] = -1*cofactors[2,3]
cofactors[3,2] = -1*cofactors[3,2]

cofactors
##       a  b  c
## [1,] -2 -3 -2
## [2,]  4 -2 -1
## [3,]  2 -4  2

For each cell, get minors.

minors <- matrix(NA,nrow=3,ncol=3)
for(i in 1:3)
{
    for(j in 1:3)
    {
        remaining_rows <- setdiff(1:3,i)
        remaining_cols <- setdiff(1:3,j)
        a = mymatrix[min(remaining_rows),min(remaining_cols)]
        b = mymatrix[min(remaining_rows),max(remaining_cols)]
        c = mymatrix[max(remaining_rows),min(remaining_cols)]
        d = mymatrix[max(remaining_rows),max(remaining_cols)]
        minors[i,j] <- a*d - b*c
    }
}

minors
##      [,1] [,2] [,3]
## [1,]   -8  -10  -12
## [2,]   14    0  -14
## [3,]   -1  -10   16

For each row in cofactors, multiply by the appropriate values from minors to show that it does not matter which row you use to get determinant.

for(i in 1:3)
{
    print(paste0("Testing row ",i))
    print("Cofactors:")
    print(as.vector(cofactors[i,]))
    print("Minors:")
    print(as.vector(minors[i,]))
    print("Product:")
    print(as.vector(cofactors[i,]) * as.vector(minors[i,]))
    print("Determinant:")       
    print(sum(as.vector(cofactors[i,]) * as.vector(minors[i,])))
    print("")
}
## [1] "Testing row 1"
## [1] "Cofactors:"
## [1] -2 -3 -2
## [1] "Minors:"
## [1]  -8 -10 -12
## [1] "Product:"
## [1] 16 30 24
## [1] "Determinant:"
## [1] 70
## [1] ""
## [1] "Testing row 2"
## [1] "Cofactors:"
## [1]  4 -2 -1
## [1] "Minors:"
## [1]  14   0 -14
## [1] "Product:"
## [1] 56  0 14
## [1] "Determinant:"
## [1] 70
## [1] ""
## [1] "Testing row 3"
## [1] "Cofactors:"
## [1]  2 -4  2
## [1] "Minors:"
## [1]  -1 -10  16
## [1] "Product:"
## [1] -2 40 32
## [1] "Determinant:"
## [1] 70
## [1] ""