Ask Your Question

Revision history [back]

If you know that you are dealing with 5x4 matrices, for example:

sage: A = random_matrix(QQ, 5, 4)
sage: A in MatrixSpace(ZZ, 5, 4)
False

Or if you don't know the size:

sage: A in MatrixSpace(ZZ, A.nrows(), A.ncols())
False

This seems to be a little faster than all(x in ZZ for x in A.list()), especially as the matrices get large.

sage: %timeit all(a in ZZ for a in random_matrix(QQ, 200, 200).list())
100 loops, best of 3: 15.5 ms per loop
sage: %timeit random_matrix(QQ, 200, 200) in MatrixSpace(ZZ, 200, 200)
100 loops, best of 3: 3.32 ms per loop

If you know that you are dealing with 5x4 matrices, for example:

sage: A = random_matrix(QQ, 5, 4)
sage: A in MatrixSpace(ZZ, 5, 4)
False

Or if you don't know the size:

sage: A in MatrixSpace(ZZ, A.nrows(), A.ncols())
False

This seems to be a little faster than all(x in ZZ for x in A.list()), especially as the matrices get large.

sage: %timeit all(a in ZZ for a in random_matrix(QQ, 200, 200).list())
100 loops, best of 3: 15.5 ms per loop
sage: %timeit random_matrix(QQ, 200, 200) in MatrixSpace(ZZ, 200, 200)
100 loops, best of 3: 3.32 ms per loop

Revised timings to also compare the denominator method (on a different computer, so all of the timings are different):

sage: %timeit all(a in ZZ for a in random_matrix(QQ, 200, 200).list())
100 loops, best of 3: 16.2 ms per loop
sage: %timeit random_matrix(QQ, 200, 200) in MatrixSpace(ZZ, 200, 200)
100 loops, best of 3: 3.44 ms per loop
sage: %timeit random_matrix(QQ, 200, 200).denominator() == 1
100 loops, best of 3: 3.77 ms per loop