Esempio n. 1
0
        /// <summary>
        /// Method is used to get a determinant of the required matrix.
        /// </summary>
        /// <param name="matrix">Initial matrix to get determinant.</param>
        /// <returns>Matrix determinant.</returns>
        public static double GetMatrixDeterminant(MatrixT <T> matrix)
        {
            if (matrix.Elements.Length == 1)
            {
                return((dynamic)matrix[0, 0]);
            }

            if (matrix.Elements.Length == 4)
            {
                return((dynamic)matrix[0, 0] * (dynamic)matrix[1, 1] - (dynamic)matrix[0, 1] * (dynamic)matrix[1, 0]);
            }

            double sign   = 1;
            double result = 0;

            for (int i = 0; i < matrix.Elements.GetLength(1); i++)
            {
                T[,] minor = MatrixT <T> .GetMinor(matrix.Elements, i);

                result += sign * (dynamic)matrix[0, i] * GetMatrixDeterminant(new MatrixT <T>(minor));

                sign = -sign;
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Method is used to take inversed matrix.
        /// </summary>
        /// <param name="matrix">Initial matrix.</param>
        /// <returns>Inversed matrix.</returns>
        public static MatrixT <T> GetInverseMatrix(MatrixT <T> matrix)
        {
            double determinant = MatrixT <T> .GetMatrixDeterminant(matrix);

            if (determinant != 0)
            {
                MatrixT <T> reversedMatrix = new MatrixT <T>(matrix.Rows, matrix.Columns);

                for (int i = 0; i < matrix.Rows; i++)
                {
                    for (int j = 0; j < matrix.Columns; j++)
                    {
                        MatrixT <T> tempMatrix = MatrixT <T> .GetMinor(matrix, i, j);

                        reversedMatrix[i, j] = (dynamic)Math.Pow(-1.0, i + j + 2) * (dynamic)MatrixT <T> .GetMatrixDeterminant(tempMatrix) / (dynamic)determinant;
                    }
                }

                return(MatrixT <T> .TransponeMatrix(reversedMatrix));
            }

            return(null);
        }