Example #1
0
        /// <summary>
        /// Returns adjugate matrix
        ///
        /// O(N^5)
        /// </summary>
        public GenTensor <T> Adjoint()
        {
            #if ALLOW_EXCEPTIONS
            if (!IsSquareMatrix)
            {
                throw new InvalidShapeException("Matrix should be square");
            }
            #endif
            var diagLength = Shape.shape[0];
            var res        = GenTensor <T> .CreateSquareMatrix(diagLength);

            var temp = SquareMatrixFactory <T> .GetMatrix(diagLength);

            if (diagLength == 1)
            {
                res.SetValueNoCheck(ConstantsAndFunctions <T> .CreateOne(), 0, 0);
                return(res);
            }

            var toNegate = false;

            for (int x = 0; x < diagLength; x++)
            {
                for (int y = 0; y < diagLength; y++)
                {
                    GetCofactor(this, temp, x, y, diagLength);
                    toNegate = (x + y) % 2 == 1;
                    var det = temp.DeterminantGaussianSafeDivision(diagLength - 1);
                    if (toNegate)
                    {
                        res.SetValueNoCheck(ConstantsAndFunctions <T> .Negate(det), y, x);
                    }
                    else
                    {
                        res.SetValueNoCheck(det, y, x);
                    }
                }
            }

            return(res);
        }