/// <summary> /// generates the inverse of a matrix /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static Matrix GetInverse(Matrix matrix) { if (matrix == null) { throw new ArgumentNullException(); } // todo: is returning null the best option? if (!matrix.isInvertible()) { return(null); } int n = matrix.rows; Matrix toRref = new Matrix(n, 2 * n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { toRref[i, j] = matrix[i, j]; } for (int j = n; j < 2 * n; j++) { toRref[i, j] = 0; } toRref[i, i + n] = 1; } Matrix rref = RREF(toRref); Matrix result = new Matrix(n, n); for (int i = 0; i < n; i++) { for (int j = n; j < 2 * n; j++) { result[i, j - n] = rref[i, j]; } } return(result); }