Ask Your Question

Generate a random non-singular matrix?

asked 2019-03-01 06:44:45 +0200

anonymous user


I do this in a loop now:

    A = random_matrix(...)  
    if(not A.is_singular()):  

But this is innefficient. How do I generate random matrices with more concrete properties in sage?

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted

answered 2019-03-01 20:39:47 +0200

You could do it one row at a time by choosing random vectors:

def random_nonsingular_matrix(base_ring=QQ, size=3):
    V = base_ring**size
    vectors = []
    for i in range(size):
        v = V.random_element()
        while v in V.span(vectors):
            v = V.random_element()


sage: random_nonsingular_matrix(size=4).determinant()
sage: random_nonsingular_matrix(size=4).determinant()
sage: random_nonsingular_matrix(size=4).determinant()
sage: random_nonsingular_matrix(size=4).determinant()

It's unfortunately much slower than random_matrix:

sage: %timeit random_nonsingular_matrix(size=20)
10 loops, best of 3: 84.9 ms per loop
sage: %timeit random_matrix(QQ, 20, 20)
10000 loops, best of 3: 58.2 µs per loop
edit flag offensive delete link more

answered 2019-03-01 07:04:04 +0200

slelievre gravatar image

The documentation helps with that.

It can be accessed using

sage: random_matrix?

and in particular hints at

sage: random_matrix(algorithm='unimodular')

which will return a matrix of determinant one.

edit flag offensive delete link more


What about constructing a matrix of determinant K?

rijndaelxyz gravatar imagerijndaelxyz ( 2019-03-01 07:43:34 +0200 )edit

One could start from a determinant one matrix and multiply one row or one column by K.

One could then multiply by another random determinant one matrix (on the left or on the right or both) to mix things up a bit more.

slelievre gravatar imageslelievre ( 2019-03-01 17:35:13 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-03-01 06:44:45 +0200

Seen: 1,797 times

Last updated: Mar 01 '19