double determinant(Matrix& A) { if ((A.m_rows != A.m_columns) || A.m_rows<1)//no need to check columns too for <1 { return 0; } else if (A.m_rows == 1){ return A.mat[0]; } //else if (A.m_rows == 2) //{ // // A // // [ 0 1 ] // // [ 2 3 ] // // // return (A.mat[0] * A.mat[3] - A.mat[1] * A.mat[2]); //} else { double det=0; for (int i = 0; i < A.m_columns; i++) { Matrix temp = A; double coefficient = pow(-1.0, i)*A.mat[i]; temp.DeleteColumn(i); temp.DeleteRow(0); det += coefficient*determinant(temp);//recursion here :D } return det; } }
Matrix Matrix::inverse() { if (determinant(*this) == 0 || (m_rows != m_columns)) //Actually need to check too if max(Coffactors[])* 1/det ->OVERFLOW { return *this;//do nothing } else { Matrix Cofactors(m_rows, m_columns); //Compute the Coffactor elementes for (int i = 0; i < Cofactors.m_columns; i++) { for (int j = 0; j < Cofactors.m_rows; j++) { Matrix temp = *this; double coefficient = pow(-1.0, i + j) /* *A.mat[j*A.m_columns + i]*/; temp.DeleteColumn(i); temp.DeleteRow(j); Cofactors.mat[j*m_columns + i] = coefficient*determinant(temp); } } Matrix Inverse = Cofactors.traspose() / determinant(*this); return Inverse; } }
void invert(Matrix& A) { if (determinant(A) == 0 || (A.m_rows!=A.m_columns)) //Actually need to check too if max(Coffactors[])* 1/det ->OVERFLOW { } else { Matrix Cofactors(A.m_rows, A.m_columns); //Compute the Coffactor elementes for (int i = 0; i < Cofactors.m_columns; i++) { for (int j = 0; j < Cofactors.m_rows; j++) { Matrix temp = A; double coefficient = pow(-1.0, i + j) ; temp.DeleteColumn(i); temp.DeleteRow(j); Cofactors.mat[j*A.m_columns + i] = coefficient*determinant(temp); } } Matrix Inverse = Cofactors.traspose() / determinant(A); A = Inverse; } }
void NormalEquations::Diagnostics() { CalculateResiduals(); CalculateCovariances(); cholesky.BackSubst(residuals); rawQ = residuals.InnerProduct(cholesky.x); Q = sqrt(2.0 * rawQ) - sqrt(2.0 * residuals.dim - 1.0); Qi.Dimension(residuals.dim); Matrix M; Vector v, r; Cholesky chol; for (int i = 0; i < residuals.dim; i++) { M = varMatrix; v = M[i]; M.DeleteColumn(i); M.DeleteRow(i); v.DeleteDimension(i); chol.Decompose(M); chol.BackSubst(v); double var = varMatrix[i][i] - v.InnerProduct(chol.x); r = residuals; r.DeleteDimension(i); chol.BackSubst(r); Qi[i] = residuals[i] - v.InnerProduct(chol.x); Qi[i] = Qi[i] * Qi[i] / var; } }