Esempio n. 1
0
    static void Main()
    {
        var rnd = new Random(1);
        int n   = 4;
        var A   = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A[i, j] = 2 * (rnd.NextDouble() - 0.5);
            }
        }
        A.print("Matrix inverse.\nRandom square matrix A:");
        var qra = new gramschmidt(A);

        var B = qra.inverse();

        B.print("\nThe inverse of A, A^-1:");
        var Id = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            Id[i, i] = 1;
        }
        var C = A * B;

        C.print("\ncheck: A*A^-1:");
        if (Id.approx(A * B))
        {
            Write("\nA*A^-1 = Id, test passed\n");
        }
        else
        {
            Write("\nA*A^-1 != Id, test failed\n");
        }
        var D = B * A;

        D.print("\ncheck: A^-1*A=");
        if (Id.approx(B * A))
        {
            Write("\nA^-1*A = I, test passed\n");
        }
        else
        {
            Write("\nA^-1*A != I, test failed\n");
        }
    }
Esempio n. 2
0
    static void Main()
    {
        /// Test on random matrix ///
        WriteLine("/////////////// Part A - Test on random matrix ///////////////");
        int n    = 5;
        var rand = new Random(1);

        matrix A = new matrix(n, n);
        vector e = new vector(n);
        matrix V = new matrix(n, n);


        for (int i = 0; i < n; i++)
        {
            for (int j = i; j < n; j++)
            {
                A[i, j] = rand.NextDouble();
                A[j, i] = A[i, j];
            }
        }

        A.print($"random {n}x{n} matrix"); WriteLine();
        matrix B      = A.copy();
        int    sweeps = jacobi.cyclic(B, e, V);

        WriteLine($"Number of sweeps in jacobi={sweeps}"); WriteLine();

        matrix D = (V.T * A * V);

        (D).print("Should be a diagonal matrix V.T*B*V="); WriteLine();
        e.print("Eigenvalues should equal the diagonal elements above");

        vector D_diagonal = new vector(n);

        for (int i = 0; i < n; i++)
        {
            D_diagonal[i] = D[i, i];
        }
        if (D_diagonal.approx(e))
        {
            WriteLine("Eigenvalues agree \tTest passed");
        }
        else
        {
            WriteLine("Test failed");
        }
        WriteLine();

        matrix A2 = (V * D * V.T);

        (A2).print("Check that V*D*V.T=A");
        if (A2.approx(A))
        {
            WriteLine("V*D*V.T = A \tTest passed");
        }
        else
        {
            WriteLine("V*D*V.T != A \tTest failed");
        }
    }
Esempio n. 3
0
    static void Main()
    {
        var rand = new Random();

        // We can pull out new random numbers between 0 and 1 with rand.NextDouble() and
        // stuff it into a matrix
        int    n = 4;
        matrix A = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A[i, j] = 2 - 4 * rand.NextDouble();
            }
        }
        WriteLine("Set up a random matrix, and try to find the inverse matrix via QR" +
                  " decomposition.\n");
        WriteLine("Printing random matrix A:");
        A.print();

        // Factorize the matrix into two matrices Q and R, and calculate the inverse matrix B
        var    qrGS = new qrDecompositionGS(A);
        matrix B    = qrGS.inverse();
        matrix Q    = qrGS.Q;
        matrix R    = qrGS.R;

        WriteLine("\nPrinting matrix R:");
        R.print();

        WriteLine("\nPrinting matrix Q:");
        Q.print();

        WriteLine("\nPrinting matrix B (inverse to A):");
        B.print();

        // Let's check if B is actually the inverse by calculating A*B which then should
        // give the identity matrix
        matrix AB = A * B;

        WriteLine("\nPrinting matrix A*B:");
        AB.print();

        matrix I = new matrix(n, n);

        I.set_identity();
        bool approx = AB.approx(I);

        if (approx == true)
        {
            WriteLine("A*B is approximately equal to the identity matrix.");
        }
        else
        {
            WriteLine("A*B is not approximately equal to the identity matrix.");
        }
    }
Esempio n. 4
0
    static void Main(string[] args)
    {
        int    n = 5;
        matrix D = GenRandSymMatrix(n, n);
        matrix A = D.copy();

        A.print($"Symmetric matrix A:");
        (vector e, matrix V, int n1) = cyclic(D);
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                D[j, i] = D[i, j];                 // complete the matrix
            }
        }
        matrix VTAV = V.transpose() * A * V;

        e.print($"Eigenvalues e:");
        V.print($"Eigenvectors V:");
        A.print($"D matrix: ");
        VTAV.print($"Matrix V^TAV:");
        if (D.approx(VTAV))
        {
            WriteLine("V^TAV = D, test passed.");
        }
        else
        {
            WriteLine("V^TAV != D, test failed.");
        }

        matrix B = A.copy();

        (vector e2, _, int n2) = lowest_eigens(A, 3);
        (vector e4, _, int n4) = highest_eigens(A, 3);
        e.print($"\nEigenvalues from cyclic method found after {n1, 3} rotations:               ");
        e2.print($"3 lowest eigenvalues from row-by-row method found after {n2, 3} rotations:  ");
        e4.print($"3 highest eigenvalues from row-by-row method found after {n4, 3} rotations: ");

        (vector e3, _, int n3) = classic(B);
        e3.print($"Eigenvalues from the classic method found after {n3, 3} rotations:          ");
        WriteLine();
    }
Esempio n. 5
0
    static void Main()
    {
        int    n = 4, m = 3;
        matrix A   = new matrix(n, m);                          /* Construction of a random matrix A */
        var    rnd = new Random(1);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                A[i, j] = 2 * (rnd.NextDouble() - 0.5);
            }
        }
        A.print($"QR-decomposition:\nrandom {n}x{m} matrix A:");

        var qra = new gramschmidt(A);
        var Q   = qra.Q;
        var R   = qra.R;

        Q.print("matrix Q:");
        R.print("matrix R:");
        matrix qtq = (Q.T * Q);

        qtq.print("Q^T*Q:");
        matrix qr = (Q * R);

        qr.print("Q*R:");
        if (A.approx(Q * R))
        {
            Write("Q*R=A, test passed\n");
        }
        else
        {
            Write("Q*R!=A, test failed\n");
        }
    }
Esempio n. 6
0
    public static int Main()
    {
        int    n    = 5;
        int    m    = 4;
        matrix A    = new matrix(n, m);
        var    rand = new Random(1);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                A[i, j] = 10 * (rand.NextDouble());
            }
        }


        // A.1
        WriteLine("Assignment A.1:");
        A.print($"Matrix A {n}x{m}:");
        var qr_A = new qrdecompositionGS(A);
        var Q    = qr_A.Q;
        var R    = qr_A.R;

        R.print($"The upper triangular matrix R:");
        var qq = Q.transpose() * Q;

        qq.print($"Q^T Q =1: ");
        var qr = Q * R;

        qr.print($"Q*R=A: ");
        if (A.approx(Q * R))
        {
            Write("Q*R=A, test passed\n");
        }
        else
        {
            Write("Q*R!=A, test failed\n");
        }
        WriteLine("");
        // A.2
        WriteLine("Assignment A.2:");
        matrix A2 = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A2[i, j] = 10 * (rand.NextDouble());
            }
        }
        A2.print($"Matrix A {n}x{n}:");
        var    qr_A2 = new qrdecompositionGS(A2);
        vector b     = new vector(n);

        for (int i = 0; i < n; i++)
        {
            b[i] = 10 * (rand.NextDouble());
        }
        b.print($"Vector b with size {n}: ");
        var qrxb = qr_A2.solve(qr_A2.Q, b);

        qrxb.print($"solve x for QRx=b:\nx = ");
        var ax = A2 * qrxb;

        ax.print("Ax = ");
        WriteLine("which is equal to b.\n");
        return(0);
    }
Esempio n. 7
0
    static void Main()
    {
        /// Test on random matrix ///
        WriteLine("/////////////// Part B - test of row by row method///////////////");

        int n    = 5;
        var rand = new Random(1);

        matrix A = new matrix(n, n);
        vector e = new vector(n);
        matrix V = new matrix(n, n);


        for (int i = 0; i < n; i++)
        {
            for (int j = i; j < n; j++)
            {
                A[i, j] = 2 * (rand.NextDouble() - 0.5);
                A[j, i] = A[i, j];
            }
        }

        A.print($"random {n}x{n} matrix"); WriteLine();
        matrix B = A.copy();

        int reps = jacobi_row.row(B, e, n, V);

        WriteLine($"Number of repititions in jacobi={reps}"); WriteLine();


        matrix D = (V.T * A * V);

        (D).print("Should be a diagonal matrix V.T*B*V="); WriteLine();
        e.print("Eigenvalues should equal the diagonal elements above"); WriteLine();

        vector D_diagonal = new vector(n);

        for (int i = 0; i < n; i++)
        {
            D_diagonal[i] = D[i, i];
        }
        if (D_diagonal.approx(e))
        {
            WriteLine("Test passed");
        }
        else
        {
            WriteLine("Test failed");
        }

        matrix A2 = (V * D * V.T);

        (A2).print("Check that V*D*V.T=A"); WriteLine();
        if (A2.approx(A))
        {
            WriteLine("V*D*V.T = A \tTest passed");
        }
        else
        {
            WriteLine("V*D*V.T != A \tTest failed");
        }


        WriteLine(); WriteLine();
        WriteLine("/////////////// Find only the higest eigen values///////////////");

        vector e1    = new vector(n);
        matrix V1    = new matrix(n, n);
        string order = "high";

        A.print($"random {n}x{n} matrix"); WriteLine();
        matrix C = A.copy();

        int reps1 = jacobi_row.row(C, e1, 2, V1, order);

        WriteLine($"Number of repititions in jacobi={reps1}"); WriteLine();


        matrix D1 = (V1.T * A * V1);

        (D1).print("First two diagonal elements should be the two higest eigenvalues");

        WriteLine();
        vector D1_diagonal2highest = new vector(D1[0, 0], D1[1, 1]);
        vector D_diagonal2highest  = new vector(D[n - 1, n - 1], D[n - 2, n - 2]);

        if (D1_diagonal2highest.approx(D_diagonal2highest))
        {
            WriteLine("Eigenvalues match \tTest passed");
        }
        else
        {
            WriteLine("Eigenvalues do not match \tTest failed");
        }
    }
Esempio n. 8
0
    public static void Main(string[] args)
    {
        int    n = 5;
        matrix A = myMatrixMethods.randMatrix(n, n);

        // Make A symetrical
        myMatrixMethods.mirrorLower(A);
        A.print($"A is a symetrical matrix of size {n}");
        matrix V = new matrix(n, n);
        vector e = new vector(n);

        int sweeps = jacobi.cyclic(A, V, e);
        //V.print("Eigenvectors for A:");

        matrix D = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            D[i, i] = e[i];
        }
        D.print("The diagonal composition, D:");
        // Restore A to the original symetrical matrix
        myMatrixMethods.mirrorLower(A);
        matrix test = V.transpose() * A * V;

        test.print("Test that V^T * A * V = D");
        if (test.approx(D, 1e-5))
        {
            WriteLine("V^T * A * V == D - Works as intended");
        }
        else
        {
            WriteLine("V^T * A * V != D - Not as intended! Try again!");
        }

        WriteLine("");

        matrix test2 = V * D * V.transpose();

        test2.print("Test that V * D * V^T = A");
        if (test2.approx(A))
        {
            WriteLine("V * D * V^T == A - Works as intended");
        }
        else
        {
            WriteLine("V * A * V^T != A - Not as intended! Try again!");
        }

        WriteLine("");
        WriteLine("----- Particle in a box -----");

        // Generate a Hamiltonian
        n = 30;
        double s = 1.0 / (n + 1);
        matrix H = new matrix(n, n);

        for (int i = 0; i < n - 1; i++)
        {
            H[i, i]     = -2;
            H[i, i + 1] = 1;
            H[i + 1, i] = 1;
        }
        H[n - 1, n - 1] = -2;
        H = -(n + 1) * (n + 1) * H;

        // Diagonolize H
        V = new matrix(n, n);
        vector eigenvals = new vector(n);

        sweeps = 0;
        sweeps = jacobi.cyclic(H, V, eigenvals);

        // Check that the eigenvalues are correct
        WriteLine("E_n \t calculated \t exact");
        for (int k = 0; k < n / 3; k++)
        {
            double exact      = PI * PI * (k + 1) * (k + 1);
            double calculated = eigenvals[k];
            WriteLine($"E_{k} \t {calculated.ToString("F5")} \t {exact.ToString("F5")}");
        }

        // preparing data to be plotted
        using (StreamWriter sw = new StreamWriter("data.txt")){
            sw.WriteLine($"0 \t 0 \t 0 \t 0 \t 0 ");
            for (int i = 0; i < n; i++)
            {
                sw.Write($"{(i + 1) * 1.0 / (n + 1)}");
                for (int j = 0; j < 4; j++)
                {
                    sw.Write($"\t {V[i, j]} ");
                }
                sw.Write("\n");
            }
            sw.WriteLine($"1 \t 0 \t 0 \t 0 \t 0");
        }


        WriteLine("");
        WriteLine("");
        WriteLine("----- Problem B -----");
        n = 7;
        A = myMatrixMethods.randMatrix(n, n);
        myMatrixMethods.mirrorLower(A);
        A.print("Matrix A:");
        V = new matrix(n, n);
        e = new vector(n);
        jacobi.cyclic(A, V, e);
        e.print("Has the eigenvals:");

        myMatrixMethods.mirrorLower(A);
        int    kLowest          = n - 1;
        vector kLowestEigenvals = jacobi.kLowestEigen(A, V, e, kLowest);

        kLowestEigenvals.print($"The {kLowest} lowest eigenvals are:");



        myMatrixMethods.mirrorLower(A);
        int    kHighest          = 3;
        vector kHighestEigenvals = jacobi.kHighestEigen(A, V, e, kHighest);

        kHighestEigenvals.print($"The {kHighest} highest eigenvals are:");
    }
Esempio n. 9
0
    static void Main()
    {
        //// Del A ////

        int    n = 3;
        matrix A = rand_matrix(n);

        var cd = new cholesky(A);

        var L  = cd.L;
        var LT = cd.LT;

        WriteLine("_____________________________________"); WriteLine();
        WriteLine("Part A - decomposit A into L*LT");
        (A).print("Matrix A="); WriteLine();
        (L).print("Matrix L="); WriteLine();
        (LT).print("Matrix LT="); WriteLine();

        WriteLine("Check if L*LT=A");
        matrix LLT = L * LT;

        LLT.print("L*LT="); WriteLine();
        if (A.approx(LLT))
        {
            WriteLine("L*LT=A\tTEST PASSED");
        }
        else
        {
            WriteLine("L*LT!=A\tTEST FAILED");
        }


        //// Del B ////

        vector v = rand_vector(n);
        vector b = v.copy();

        vector x = cd.solve(v);

        WriteLine("_____________________________________"); WriteLine();
        WriteLine("Part B - Solving linear equation: A*x=b");
        A.print("Matrix A="); WriteLine();
        b.print("Vector b="); WriteLine();
        x.print("Solution x="); WriteLine();

        vector Ax = (A * x);

        Ax.print("Check A*x="); WriteLine();

        if (b.approx(Ax))
        {
            WriteLine("A*x=b   TEST PASSED");
        }
        else
        {
            WriteLine("A*x!=b  TEST FAILED");
        }

        //// Del C ////

        WriteLine("_____________________________________"); WriteLine();
        WriteLine("Part C - Determinant of A");
        double D = cd.determinant();

        WriteLine($"det(A)={D}"); WriteLine();

        //Determinant test is only avalible for n=3
        if (n == 3)
        {
            double D_alt = A[0, 0] * A[1, 1] * A[2, 2] + A[0, 1] * A[1, 2] * A[2, 0]
                           + A[0, 2] * A[1, 0] * A[2, 1] - A[0, 2] * A[1, 1] * A[2, 0]
                           - A[0, 1] * A[1, 0] * A[2, 2] - A[1, 2] * A[2, 1] * A[0, 0];
            if (matrix.approx(D_alt, D))
            {
                WriteLine("TEST PASSED");
            }
            else
            {
                WriteLine("TEST FAILED");
            }
        }

        //// Del D ////

        WriteLine("_____________________________________"); WriteLine();
        WriteLine("Part D - find the inverse matrix of A");
        var A_inv = cd.inverse();

        A_inv.print("A_inv="); WriteLine();

        WriteLine("Check if A_inv is the inverse:"); WriteLine();
        matrix AA_inv1 = A * A_inv;

        AA_inv1.print("A*A_inv="); WriteLine();
        matrix AA_inv2 = A * A_inv;

        AA_inv2.print("A_inv*A="); WriteLine();


        matrix I = matrix.id(n);

        if (I.approx(AA_inv1) && I.approx(AA_inv2))
        {
            WriteLine("A*A_inv=I\tTEST PASSED");
        }
        else
        {
            WriteLine("A*A_inv=I\tTEST FAILED");
        }
    } //Method: Main
Esempio n. 10
0
    static void Main()
    {
        // Part 1 of exercise A
        WriteLine("-------Part 1 of exercise A:-------\n");
        // We start out by creating a random matrix.
        var rand = new Random();

        // We can pull out new random numbers between 0 and 1 with rand.NextDouble() and
        // stuff it into a matrix
        int    nA = 5;
        int    mA = 4;
        matrix A  = new matrix(nA, mA);

        for (int i = 0; i < nA; i++)
        {
            for (int j = 0; j < mA; j++)
            {
                A[i, j] = 2 - 4 * rand.NextDouble();
            }
        }

        // Print A
        WriteLine("We will setup a random tall matrix and perform QR factorization on it.");
        WriteLine("Printing random tall matrix A:");
        A.print();

        // We can now try to factorize the matrix A into the two matríces Q and R
        var    qrGSA = new qrDecompositionGS(A);
        matrix Q     = qrGSA.Q;
        matrix R     = qrGSA.R;

        // Let's check that R is upper triangular
        WriteLine("\nPrinting matrix R:");
        R.print();


        WriteLine("\nPrinting matrix Q:");
        Q.print();

        // Checking that Q^T * Q = 1
        WriteLine("\nPrinting (Q^T)*Q:");
        matrix QTQ = Q.transpose() * Q;

        QTQ.print();

        // Let's check if (Q^T)*Q is approximately the identity matrix
        matrix I = new matrix(mA, mA);

        I.set_identity();
        bool approx = QTQ.approx(I);

        if (approx == true)
        {
            WriteLine("(Q^T)*Q is approximately equal to the identity matrix.");
        }
        else
        {
            WriteLine("(Q^T)*Q is not approximately equal to the identity matrix.");
        }


        // Checking that Q*R=A, or in other words that A-Q*R = 0
        WriteLine("\nPrinting out A-Q*R:");
        matrix AmQR = A - Q * R;

        AmQR.print();

        // Let's check if Q*R is approximately equal to A, or that A-QR is approx. the zero
        // matrix
        matrix nullMatrix = new matrix(AmQR.size1, AmQR.size2);

        nullMatrix.set_zero();

        approx = AmQR.approx(nullMatrix);
        if (approx == true)
        {
            WriteLine("QR is thus approximately equal to A.");
        }
        else
        {
            WriteLine("QR is thus not approximately equal to A.");
        }



        // Part 2 of exercise A
        WriteLine("\n\n-------Part 2 of exercise A:-------\n");

        // At first we create a random square matrix - let's call it C now to avoid confusion
        // with part 1 above
        WriteLine("Setting up system C*x = b.");
        int    nC = 4;
        matrix C  = new matrix(nC, nC);

        for (int i = 0; i < nC; i++)
        {
            for (int j = 0; j < nC; j++)
            {
                C[i, j] = 2 - 4 * rand.NextDouble();
            }
        }
        WriteLine("Printing matrix C:");
        C.print();

        // Next we generate a vector b of a length corresponding to the dimension of the
        // square matrix
        vector b = new vector(nC);

        for (int i = 0; i < nC; i++)
        {
            b[i] = 3 * rand.NextDouble() - 1.5;
        }
        WriteLine("\nPrinting out b:");
        b.print();

        // Once again we factorize our matrix into two matrices Q and R
        var qrGSC = new qrDecompositionGS(C);

        Q = qrGSC.Q;
        R = qrGSC.R;

        WriteLine("\nSolving by QR decomposition and back-substitution.");
        vector x = qrGSC.solve(b);

        WriteLine("\nThe obtained x-vector from the routine is:");
        x.print();

        WriteLine("\nPrinting vector C*x :");
        vector Cx = C * x;

        Cx.print();

        // Let's check if C*x is approximately equal to b
        approx = Cx.approx(b);
        if (approx == true)
        {
            WriteLine("Cx is approximately equal to b. The system has been solved.");
        }
        else
        {
            WriteLine("Cx is not approximately equal to b. The system has not been solved.");
        }
    }
Esempio n. 11
0
    static void Main()
    {
        WriteLine("_____________________________________");
        WriteLine("Part C1 - decomposition of random matrix A");

        int    n    = 5;
        matrix A    = new matrix(n, n);
        var    rand = new Random(1);

        // make random matrix A
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A[i, j] = 2 * (rand.NextDouble() - 0.5);
            }
        }


        vector b = new vector(n);

        // make random vector b
        for (int i = 0; i < n; i++)
        {
            b[i] = 2 * (rand.NextDouble() - 0.5);
        }

        // make the QR decomposition through givens-rotation
        var qr1 = new givens(A);
        // Matrix with R in the right diagonal and givens-angels in the lower sub-diagonal
        var G = qr1.G;

        // make the QR decomposition through GS
        var qr2 = new gs(A);
        var R   = qr2.R;



        A.print("Matrix A="); WriteLine();
        WriteLine("Upper triangular part of matrix G contains the elements of R.");
        WriteLine("The enteries below the diagonal of G contains givens-rotation angles.");
        G.print("Matrix G="); WriteLine();
        R.print("Matrix R="); WriteLine();
        WriteLine("The upper triangular part of G should match the elements in R achived through GS.");

        //Filter out the lower part of G
        matrix R2 = G.copy();

        for (int j = 0; j < G.size2; j++)
        {
            for (int i = j + 1; i < G.size1; i++)
            {
                R2[i, j] = 0;
            }
        }

        if (R2.approx(R))
        {
            WriteLine("Upper triangular part identical - TEST PASSED");
        }
        else
        {
            WriteLine("Upper triangular part not identical - TEST FAILED");
        }

        WriteLine("_____________________________________");
        WriteLine("Part C2 - solve the linear equations of A*x=b"); WriteLine();

        // solve the equation A*x=b for vector x
        var x = qr1.solve(b);

        b.print("Vector b="); WriteLine();
        x.print("Solution x="); WriteLine();

        vector Ax = (A * x);

        Ax.print("Check A*x=");
        if (b.approx(Ax))
        {
            WriteLine("A*x=b  -  TEST PASSED");
        }
        else
        {
            WriteLine("A*x!=b  -  TEST FAILED");
        }
    } //Method: Main
Esempio n. 12
0
    static void Main()
    {
        int    n = 5, m = 4;
        matrix A1  = new matrix(n, m);
        var    rnd = new Random(1);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                A1[i, j] = 2 * (rnd.NextDouble() - 0.5);
            }
        }
        WriteLine("____Assignment A1____");
        A1.print($"QR-decomposition:\nrandom {n}x{m} matrix A:");
        (matrix Q, matrix R1) = qrDecomp.qr_gs_decomp(A1);
        R1.print("matrix R:");
        matrix QTQ = Q.T * Q;
        matrix QR  = Q * R1;

        QTQ.print("Q^T*Q:");
        QR.print("Q*R:");
        if (A1.approx(QR))
        {
            WriteLine("Q*R=A, test passed");
        }
        else
        {
            WriteLine("Q*R!=A, test failed");
        }
        Write("\n\n");


        matrix A2 = new matrix(n, n);

        rnd = new Random(2);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A2[i, j] = 2 * (rnd.NextDouble() - 0.5);
            }
        }
        vector b = new vector(n);

        rnd = new Random(3);
        for (int i = 0; i < n; i++)
        {
            b[i] = 2 * (rnd.NextDouble() - 0.5);
        }
        WriteLine("____Assignment A2____");
        A2.print($"Solving system of equations A*x=Q*R*x=b:\nrandom {n}x{n} matrix A:");
        (matrix Q2, matrix R2) = qrDecomp.qr_gs_decomp(A2);
        Q2.print("matrix Q:");
        R2.print("matrix R:");
        b.print("vector b:");
        vector x2  = qrDecomp.qr_gs_solve(Q2, R2, b);
        vector Ax2 = A2 * x2;

        x2.print("solution vector x:");
        Ax2.print("A*x:");
        if (b.approx(A2 * x2))
        {
            WriteLine("A*x=b, test passed");
        }
        else
        {
            WriteLine("A*x!=b, test failed");
        }
        Write("\n\n");


        matrix A3 = new matrix(n, n);

        rnd = new Random(4);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                A3[i, j] = 2 * (rnd.NextDouble() - 0.5);
            }
        }
        WriteLine("____Assignment B____");
        A3.print($"Decomposing A into Q*R:\nrandom {n}x{n} matrix A:");
        (matrix Q3, matrix R3) = qrDecomp.qr_gs_decomp(A3);
        Q3.print("matrix Q:");
        R3.print("matrix R:");
        matrix B = qrDecomp.qr_gs_inverse(Q3, R3);
        matrix I = new matrix(n, n);

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                I[i, j] = 0;
                if (i == j)
                {
                    I[i, j] = 1;
                }
            }
        }
        I.print($"Idenity matrix I({n}):");
        B.print("Inverse matrix B:");
        matrix AB       = A3 * B;
        matrix AB_round = new matrix(n, n); // rounded matrix to 10th decimal to get a nicer output

        for (int i = 0; i <= n - 1; i++)
        {
            for (int j = 0; j <= n - 1; j++)
            {
                AB_round[i, j] = Math.Round((Double)AB[i, j], 10);
            }
        }
        AB_round.print("A*B:");
        if (AB.approx(I))
        {
            WriteLine("A*B=I, test passed");             // test is still with unrounded matrix
        }
        else
        {
            WriteLine("A*B!=I, test failed");
        }
        Write("\n\n");


        WriteLine("____Assignment C____");
        A2.print($"Givens rotation of the same coefficient matrix as in part A(2):\nrandom {n}x{m} matrix A:");
        matrix T = A2.copy();

        qrDecomp.qr_givens_decomp(T);
        T.print("Matrix with R in the upper trinagle and angles of the Givens rotation below, T:");
        b.print("Same vector b as in A(2):");
        vector Gb  = b.copy();
        vector x4  = qrDecomp.qr_givens_solve(T, Gb);
        vector Ax4 = A2 * x4;

        x4.print("solution vector x:");
        Ax4.print("A*x:");
        if (b.approx(A2 * x4))
        {
            WriteLine("A*x=b, test passed");
        }
        else
        {
            WriteLine("A*x!=b, test failed");
        }
        Write("\n\n");
    }
Esempio n. 13
0
    static void Main(string[] args)
    {
        int n = 3, m = 3;

        // QR DECOMPOSITION
        writetitle("\nQR decomposition");
        matrix A = GenRandMatrix(n, m);
        matrix R = new matrix(m, m);
        matrix Q = A.copy();

        A.print($"QR-decomposition of the matrix A:");
        gs.decomp(Q, R);
        R.print($"Matrix R:");
        var QQT = Q.T * Q;    // does not work within parantheses
        var QR  = Q * R;      // same

        QQT.print("Q^T Q:");
        QR.print("QR:");
        if (A.approx(QR))
        {
            writepass("QR = A, test passed.");
        }
        else
        {
            writefail("QR != A, test failed.");
        }

        // SOLVING
        writetitle("\nQR solving");
        A = GenRandMatrix(n, m);
        vector b = GenRandVector(m);

        R = new matrix(m, m);
        //A[0, 0] = 1; A[0, 1] = 1; A[0, 2] = 1;
        //A[1, 0] = 0; A[1, 1] = 2; A[1, 2] = 5;
        //A[2, 0] = 2; A[2, 1] = 5; A[2, 2] = -1;
        //vector b = new vector(6, -4, 27);
        A.print($"Solving the equation Ax = b, with A:");
        b.print($"and b:\n");
        Q = A.copy();
        gs.decomp(Q, R);
        vector x = gs.solve(Q, R, b);

        x.print($"\nSolution is x:\n");
        var Ax = A * x;

        Ax.print($"Ax:\n");
        if (b.approx(Ax))
        {
            writepass("Ax = Q^T b, test passed.");
        }
        else
        {
            writefail("Ax != Q^T b, test failed.");
        }

        // INVERSE
        writetitle("\nQR inverse");
        A = GenRandMatrix(n, m);
        R = new matrix(m, m);
        Q = A.copy();
        gs.decomp(Q, R);
        matrix B = gs.inverse(Q, R);         // B = A^-1

        A.print($"Solving for the inverse of A:");
        B.print($"Inverse is B:");
        matrix AB = A * B;

        AB.print($"AB:");
        matrix I = new matrix(n, m);

        for (int i = 0; i < n; i++)
        {
            I[i, i] = 1;
        }
        if (AB.approx(I))
        {
            writepass("AB = I, test passed.");
        }
        else
        {
            writefail("AB != I, test failed.");
        }

        // GIVENS
        writetitle("\nGivens rotations");
        A = GenRandMatrix(n, m);
        b = GenRandVector(m);
        A.print($"Solving the equation Ax = b, with A:");
        b.print($"and b:\n");
        givens decomp = new givens(A);

        x = decomp.solve(b);
        x.print("\nSolution is x:\n");
        Ax = A * x;
        Ax.print("Ax:\n");
        if (Ax.approx(b))
        {
            writepass("Ax = b, test passed.");
        }
        else
        {
            writefail("Ax != b, test failed.");
        }
    }
Esempio n. 14
0
    static void Main(string[] args)
    {
        WriteLine("----- Problem A -----");
        WriteLine("------- testing the decomp function --------");
        int    n = 5, m = 3;
        matrix A = randMatrix(n, m);
        matrix R = new matrix(m, m);
        matrix Q = A.copy();

        A.print("QR-decomposition of the matrix A: ");
        gs.decomp(Q, R);
        R.print("The matrix R: ");
        matrix QTQ = Q.transpose() * Q;

        QTQ.print("Q^t * t: ");
        matrix QR = Q * R;

        QR.print("QR: ");
        if (QR.approx(A))
        {
            WriteLine("QR = A - Works as intended!");
        }
        else
        {
            WriteLine("QR != A - This does not work as intended. Try again!");
        }


        WriteLine("------- testing the solve function --------");
        n = 4;
        A = randMatrix(n, n);
        R = new matrix(n, n);
        Q = A.copy();
        vector b = randVector(n);

        gs.decomp(Q, R);
//		Q.print("A:");
//		R.print("R:");
//		b.print("b:");
        vector x = gs.solve(Q, R, b);

        x.print("x:");
        vector Ax = A * x;

        if (Ax.approx(b))
        {
            WriteLine("A * x == b - works as intended");
        }
        else
        {
            WriteLine("A * x != b - this is not as intended! Try again!");
        }



        WriteLine("----- Problem B -----");
        WriteLine("------- testing the inverse function --------");
        n = 6;
        A = randMatrix(n, n);
        R = new matrix(n, n);
        Q = A.copy();
        gs.decomp(Q, R);
        matrix Ai  = gs.inverse(Q, R);
        matrix AAi = A * Ai;

        AAi.print("A * Ai:");
        matrix I = new matrix(n, n);

        I.set_identity();
        if (I.approx(AAi))
        {
            WriteLine("A * Ainverse is the identity! - this is as intended!");
        }
        else
        {
            WriteLine("A * Ainverse is not the identity! - this is not as intended! Try again!");
        }
    }
Esempio n. 15
0
    static void Main(){

    //// Del A1 ////
        int n=4, m=3;
        matrix A= new matrix(n,m);
        var rand= new Random(1);
    
    
    for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
        A[i,j]=2*(rand.NextDouble()-0.5);
    }
    }
        
        var qra1=new gs(A);

        var Q=qra1.Q;
        var R=qra1.R;
        
        WriteLine("_____________________________________");
        WriteLine("Part A1 - decomposit A into Q*R");
        (A).print("Matrix A=");WriteLine();
        (Q).print("Matrix Q=");WriteLine();
        (R).print("Matrix R=");WriteLine();

        WriteLine("Check if Q.T is the inverse of Q");
        ((Q.T)*Q).print("Q.T*Q=");WriteLine();
        
        WriteLine("Check if Q*R=A");
        matrix QR=Q*R;
        QR.print("Q*R=");
        if(A.approx(QR)){WriteLine("Q*R=A\nTest passed");}
        else {WriteLine("Q*R!=A\nTest failed");}



    //// Del A2 ////
        WriteLine("_____________________________________");
        WriteLine("Part A2 - solve the linear equations of A*x=b");

        n=4;
        A=new matrix(n,n);
        for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
        A[i,j]=2*(rand.NextDouble()-0.5);
        }
        }

        vector b= new vector(n);
        for(int i=0;i<n;i++){
        b[i]=2*(rand.NextDouble()-0.5);
        }

        var qra2=new gs(A);

        var x=qra2.solve(b);
        A.print("Matrix A=");WriteLine();
        b.print("Vector b=");WriteLine();
        x.print("Solution x=");WriteLine();

        vector Ax=(A*x);
        Ax.print("Check A*x=");
        if(b.approx(Ax)){WriteLine("A*x=b   Test passed");}
        else {WriteLine("A*x!=b  Test failed");}

    //// Del B ////
        WriteLine("_____________________________________");
        WriteLine("Part B - find the inverse matrix of A");
        var A_inv=qra2.inverse();
        A_inv.print("A_inv=");WriteLine();
        
        WriteLine("Check if A_inv is the inverse:");WriteLine();
        matrix AA_inv1=A*A_inv;
        AA_inv1.print("A*A_inv=");WriteLine();
        matrix AA_inv2=A*A_inv;
        AA_inv2.print("A_inv*A=");WriteLine();

        matrix I= new matrix(n,n);
        for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
        if(i==j) I[i,j]=1;
        else    I[i,j]=0;
        }
        }

        if(I.approx(AA_inv1) || I.approx(AA_inv2)){WriteLine("A*A_inv=I\nTest passed");}
        else {WriteLine("A*A_inv=I\nTest failed");}

    } //Method: Main