Randomly Generating a Singular Matrix in Maple


  • TA School

    singular3 := proc(gen)
        #Make 2x2 Matrix w/ zero determinant
        local M, A, flag := true:
        while flag do
            M := LinearAlgebra[RandomMatrix](2,2, generator = gen):
            if LinearAlgebra:-Determinant(M) = 0 then
                    M[1,1] := (M[1,1] + 1 ) mod 10;
                    M[1,2] := (M[1,2] + 5 ) mod 10;
                    M[2,1] := (M[2,1] + 5 ) mod 10;
                    M[2,2] := (M[2,2] + 4 ) mod 10;
                fi:
     
                if LinearAlgebra:-Determinant(M) <> 0 then
                    flag := false:
                fi:
            od:     #Insert as cofactor into 3x3 Matrix
            A := Matrix([[M[1,1],M[1,2],gen()],[M[2,1],M[2,2],gen()],[gen(),gen(),1]]):     #Edit last element such that determinant is zero
        A[3,3] := -(A[3,1]*(A[1,2]*A[2,3]-A[1,3]*A[2,2])
                    -A[3,2]*(A[1,1]*A[2,3]-A[1,3]*A[2,1]))
                    /(A[1,1]*A[2,2] - A[1,2]*A[2,1]):
            
            return A: #Returns singular 3x3 matrix
            
    end proc: #re-generate until final element is a 'nice' number
    do
        qM := singular3(rand(-3..3));
        if qM[3,3] = trunc(qM[3,3]) and abs(qM[3,3]) < 4 then
            break
        fi:
    od: qM, LinearAlgebra[Determinant](qM);


Log in to reply