/** * Performs a matrix inversion operations that takes advantage of the special * properties of a covariance matrix. * * @param cov A covariance matrix. Not modified. * @param cov_inv The inverse of cov. Modified. * @return true if it could invert the matrix false if it could not. */ public static bool invert(DMatrixRMaj cov, DMatrixRMaj cov_inv) { if (cov.numCols <= 4) { if (cov.numCols != cov.numRows) { throw new ArgumentException("Must be a square matrix."); } if (cov.numCols >= 2) { UnrolledInverseFromMinor_DDRM.inv(cov, cov_inv); } else { cov_inv.data[0] = 1.0 / cov_inv.data[0]; } } else { LinearSolverDense <DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows); // wrap it to make sure the covariance is not modified. solver = new LinearSolverSafe <DMatrixRMaj>(solver); if (!solver.setA(cov)) { return(false); } solver.invert(cov_inv); } return(true); }
/** * <p> * Solves for x in the following equation:<br> * <br> * A*x = b * </p> * * <p> * If the system could not be solved then false is returned. If it returns true * that just means the algorithm finished operating, but the results could still be bad * because 'A' is singular or nearly singular. * </p> * * <p> * If repeat calls to solve are being made then one should consider using {@link LinearSolverFactory_CDRM} * instead. * </p> * * <p> * It is ok for 'b' and 'x' to be the same matrix. * </p> * * @param a A matrix that is m by n. Not modified. * @param b A matrix that is n by k. Not modified. * @param x A matrix that is m by k. Modified. * * @return true if it could invert the matrix false if it could not. */ public static bool solve(CMatrixRMaj a, CMatrixRMaj b, CMatrixRMaj x) { LinearSolverDense <CMatrixRMaj> solver; if (a.numCols == a.numRows) { solver = LinearSolverFactory_CDRM.lu(a.numRows); } else { solver = LinearSolverFactory_CDRM.qr(a.numRows, a.numCols); } // make sure the inputs 'a' and 'b' are not modified solver = new LinearSolverSafe <CMatrixRMaj>(solver); if (!solver.setA(a)) { return(false); } solver.solve(b, x); return(true); }