float CalculateDeterminant(ArbitraryMatrix _matrix) { float d = 0; if (_matrix.rows != _matrix.columns) { Debug.LogWarning("Cannot calculate determinant of non-square matrix"); return(d); } if (_matrix.rows < 1) { return(0); } else if (_matrix.rows == 1) { return(_matrix[0][0]); } else if (_matrix.rows == 2) { return((_matrix[0][0] * _matrix[1][1]) - (_matrix[1][0] * _matrix[0][1])); } else { for (int c = 0; c < _matrix.columns; c++) { d += (Mathf.Pow(-1f, (float)c) * _matrix[0][c] * CalculateDeterminant(_matrix.SubMatrix(0, c))); } return(d); } }
ArbitraryMatrix SubMatrix(int rowToRemove, int columnToRemove) { ArbitraryMatrix sm = new ArbitraryMatrix(rows - 1, columns - 1); int k = 0, l = 0; for (int r = 0; r < rows; r++) { if (r != rowToRemove) { for (int c = 0; c < columns; c++) { if (c != columnToRemove) { sm[l][k] = matrix[r][c]; k = (k + 1) % (rows - 1); if (k == 0) { l++; } } } } } return(sm); }
public static ArbitraryMatrix operator *(float scalar, ArbitraryMatrix _matrix) { ArbitraryMatrix m = new ArbitraryMatrix(_matrix.rows, _matrix.columns); for (int r = 0; r < _matrix.rows; r++) { for (int c = 0; c < _matrix.columns; c++) { m[r][c] = scalar * _matrix[r][c]; } } return(m); }
public static ArbitraryMatrix operator *(ArbitraryMatrix matrix1, ArbitraryMatrix matrix2) { if (matrix1.rows != matrix2.rows || matrix1.columns != matrix2.columns) { Debug.LogWarning("Cannot multiply matrices: matrices must have same dimensions"); return(matrix1); } ArbitraryMatrix solution = new ArbitraryMatrix(matrix1.rows, matrix2.columns); for (int r = 0; r < solution.rows; r++) { for (int c = 0; c < solution.columns; c++) { float sum = 0; for (int k = 0; k < solution.rows; k++) { sum += matrix1[r][k] * matrix2[k][c]; } solution[r][c] = sum; } } return(solution); }