Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int[][] inverse(int[][] mat) {
- int detRecip = 1 / determinate(mat);
- int[][] adj = adjugate(mat);
- return matrixMultiply(adj, detRecip));
- }
- public static int[][] matrixMultiply(int[][] mat, int mult) {
- int[][] multMatrix = clone(mat);
- for (int[] i : multMatrix) {
- for (int j : i) {
- j *= mult;
- }
- }
- return multMatrix;
- }
- public static int[][] adjugate(int[][] mat) {
- return transpose(cofactorMatrix(mat));
- }
- public static int[][] cofactorMatrix(int[][] mat) {
- int[][] cofM = new int[mat.length][mat[0].length];
- for (int i = 0; i < mat.length; i++) {
- for (int j = 0; j < mat[i].length; j++) {
- cofM[i][j] = cofactorSign(i, j) * determinant(cofactor(mat, i, j));
- }
- }
- return cofM;
- }
- public static int cofactorSign(int i, int j) {
- return (int)Math.pow(-1, i + j);
- }
- public static int determinant(int[][] mat) {
- return determinant(mat, mat.length);
- }
- public static int determinant(int[][] mat, int n) {
- int det = 0;
- if (n == 1) {
- return mat[0][0];
- }
- int sign = 1;
- int[][] cof = new int[n][n];
- for (int i = 0; i < n; i++) {
- cof = cofactor(mat, 0, i);
- det += sign * mat[0][i] * determinant(cof, n - 1);
- sign = -sign;
- }
- return det;
- }
- public static int[][] cofactor(int[][] mat, int i, int j) {
- int[][] cofactor = new int[mat.length - 1][mat[0].length - 1];
- int currCofX = 0;
- int currCofY = 0;
- for (int a = 0; a < mat.length; a++) {
- for (int b = 0; b < mat[a].length; b++) {
- if (a != i && b != j) {
- if (currCofX >= cofactor.length) {
- currCofX = 0;
- currCofY++;
- }
- cofactor[currCofX][currCofY] = mat[a][b];
- currCofX++;
- }
- }
- }
- return cofactor;
- }
- public static int[][] transpose(int[][] mat) {
- int[][] transpose = clone(mat);
- if (transpose.length == 1 && transpose[0].length == 1) {
- return transpose;
- }
- for (int i = 0; i < transpose.length; i++) {
- for (int j = i + 1; j < transpose[i].length; j++) {
- swap(transpose, i, j, j, i);
- }
- }
- return transpose;
- }
- public static void swap(int[][] mat, int x1, int y1, int x2, int y2) {
- int temp = mat[x1][y1];
- mat[x1][y1] = mat[x2][y2];
- mat[x2][y2] = temp;
- }
- public static int[][] clone(int[][] mat) {
- int[][] clone = new int[mat.length][mat[0].length];
- for (int i = 0; i < mat.length; i++) {
- for (int j = 0; j < mat[i].length; j++) {
- clone[i][j] = mat[i][j];
- }
- }
- return clone;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement