Accord.Math.Decompositions.QrDecomposition.SolveTranspose C# (CSharp) Method

SolveTranspose() public method

Least squares solution of X * A = B
Matrix column dimensions must be the same. Matrix is rank deficient.
public SolveTranspose ( double value ) : ].double[
value double Right-hand-side matrix with as many columns as A and any number of rows.
return ].double[
        public double[,] SolveTranspose(double[,] value)
        {
            if (value == null)
                throw new ArgumentNullException("value", "Matrix cannot be null.");

            if (value.GetLength(1) != qr.GetLength(0))
                throw new ArgumentException("Matrix row dimensions must agree.");

            if (!FullRank)
                throw new InvalidOperationException("Matrix is rank deficient.");

            // Copy right hand side
            int count = value.GetLength(0);
            double[,] X = value.Transpose();
            int m = qr.GetLength(0);
            int n = qr.GetLength(1);

            // Compute Y = transpose(Q)*B
            for (int k = 0; k < n; k++)
            {
                for (int j = 0; j < count; j++)
                {
                    double s = 0.0;

                    for (int i = k; i < m; i++)
                        s += qr[i, k]*X[i, j];

                    s = -s/qr[k, k];

                    for (int i = k; i < m; i++)
                        X[i, j] += s*qr[i, k];
                }
            }

            // Solve R*X = Y;
            for (int k = n - 1; k >= 0; k--)
            {
                for (int j = 0; j < count; j++)
                    X[k, j] /= Rdiag[k];

                for (int i = 0; i < k; i++)
                    for (int j = 0; j < count; j++)
                        X[i, j] -= X[k, j]*qr[i, k];
            }

            var r = new double[count,n];
            for (int i = 0; i < n; i++)
                for (int j = 0; j < count; j++)
                    r[j, i] = X[i, j];

            return r;
        }

Usage Example

        public void SolveTransposeTest()
        {
            double[,] a = 
            {
                { 2, 1, 4 },
                { 6, 2, 2 },
                { 0, 1, 6 },
            };

            double[,] b =
            {
                { 1, 0, 7 },
                { 5, 2, 1 },
                { 1, 5, 2 },
            };

            double[,] expected =
            {
                 { 0.5062,    0.2813,    0.0875 },
                 { 0.1375,    1.1875,   -0.0750 },
                 { 0.8063,   -0.2188,    0.2875 },
            };

            var target = new QrDecomposition(b, true);
            double[,] actual = target.SolveTranspose(a);
            Assert.IsTrue(Matrix.IsEqual(expected, actual, 1e-3));
            Assert.IsTrue(Matrix.IsEqual(b.Transpose(), target.Reverse(), 1e-6));

        }