# Generate a random non-singular matrix?

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?

edit retag close merge delete

Sort by » oldest newest most voted

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

more

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.

more

What about constructing a matrix of determinant K?

( 2019-03-01 00:43:34 -0600 )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.

( 2019-03-01 10:35:13 -0600 )edit