First time here? Check out the FAQ!

Ask Your Question
2

Generate a random non-singular matrix?

asked 6 years ago

anonymous user

Anonymous

I do this in a loop now:

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

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

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 6 years ago

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()
        vectors.append(v)
    return(matrix(vectors))

Examples:

sage: random_nonsingular_matrix(size=4).determinant()
1337/102
sage: random_nonsingular_matrix(size=4).determinant()
127/16
sage: random_nonsingular_matrix(size=4).determinant()
815/16
sage: random_nonsingular_matrix(size=4).determinant()
96533/326

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
Preview: (hide)
link
1

answered 6 years ago

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.

Preview: (hide)
link

Comments

What about constructing a matrix of determinant K?

rijndaelxyz gravatar imagerijndaelxyz ( 6 years ago )

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 ( 6 years ago )

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

Stats

Asked: 6 years ago

Seen: 2,108 times

Last updated: Mar 01 '19