diff --git a/src/main/java/com/mattrixwv/matrix/IntegerMatrix.java b/src/main/java/com/mattrixwv/matrix/IntegerMatrix.java index 8a23e18..c18b3ea 100644 --- a/src/main/java/com/mattrixwv/matrix/IntegerMatrix.java +++ b/src/main/java/com/mattrixwv/matrix/IntegerMatrix.java @@ -656,6 +656,32 @@ public class IntegerMatrix{ //Return the determinant return det; } + public IntegerMatrix cofactor(){ + //Make sure the matrix is square + if(!isSquare()){ + throw new InvalidGeometryException("A matrix must be square to find the cofactor matrix"); + } + + //Create a new grid + int[][] newGrid = new int[getNumRows()][getNumCols()]; + //If the grid is 1x1 return the grid + if(getNumRows() == 1){ + newGrid[0][0] = grid[0][0]; + } + //Use the formula to find the cofactor matrix + else{ + for(int row = 0;row < getNumRows();++row){ + int multiplier = ((row % 2) == 0) ? 1 : -1; + for(int col = 0;col < getNumCols();++col){ + newGrid[row][col] = multiplier * laplaceExpansionHelper(row, col).determinant(); + multiplier = -multiplier; + } + } + } + + //Return the new matrix + return new IntegerMatrix(newGrid); + } //Object funtions @Override