Ask Your Question
0

Selecting matrices with only certain entries

asked 12 years ago

GaryMak gravatar image

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?

Many thanks in advance

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 12 years ago

fidbc gravatar image

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

Comments

Thank you - I didn't realise the product construction would work in this context!!

GaryMak gravatar imageGaryMak ( 12 years ago )
0

answered 12 years ago

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

Comments

Thanks - a useful alternative perspective

GaryMak gravatar imageGaryMak ( 12 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

Stats

Asked: 12 years ago

Seen: 431 times

Last updated: Jan 21 '13