# Selecting matrices with only certain entries

Hi all -

a slightly more general but less ambitious version of my previous (as yet unanswered) question: http://ask.sagemath.org/question/2114...

I set up a matrix space M (for simplicity say over a finite field F) and I have a (finite) subset S of F. I need to do a search through the elements of M which satisfy certain algebraic constraints; however I only wish to study matrices whose entries ALL lie in S.

How please do I restrict to such matrices?

edit retag close merge delete

Sort by » oldest newest most voted Python's itertools module might be useful.

Assuming M is the matrix space (m by n matrices over F) and S is the subset of F. The following loop might do the trick:

from itertools import product
for entries in product(S,repeat=m*n):
m = M( entries )

more

Thank you - I didn't realise the product construction would work in this context!! fidelbc's answer is better than this one (because it's much faster), but here's more of a brute force technique, since it iterates through all of the elements of the matrix space M:

sage: M = MatrixSpace(GF(5), 3, 2)
sage: S = [GF(5)(_) for _ in 2,4]  # S = {2,4}
sage: [a for a in M if set(a.list()).issubset(S)]


Note the speed difference:

sage: timeit('[a for a in M if set(a.list()).issubset(S)]')
5 loops, best of 3: 5.43 s per loop


versus

sage: from itertools import product
sage: m = []
sage: timeit('for entries in product(S, repeat=6): m.append(M(entries))')
125 loops, best of 3: 1.91 ms per loop

more