# List (or set) of matrices

Hi, I am trying to write a function that will put all the 2x2 matrices over a finite field Z_p into a list or set. I am just switching from Mathematica to Sage, so this might be way off, but could you please help me go in the right direction?

def ListM(p):
var('UT')
UT=[]
for i1 in range(0,p):
for i2 in range(0,p):
for i3 in range(0,p):
for i4 in range(0,p):
UT=UT+[matrix([[i1,i2],[i3,i4]])]


I am trying to create a dummy list UT, and recursively add to it. I want it to serve as a variable though. The output gives me some error as well. I've been on it for a few hours and cant seem to figure it out.

edit retag close merge delete

Sort by » oldest newest most voted

You should mention what error you got. For creating all the 2x2 matrices over some finite field use the MatrixSpace class.

sage: M = MatrixSpace(GF(3), 2, 2)
sage: M
Full MatrixSpace of 2 by 2 dense matrices over Finite Field of size 3
sage: Mlist = M.list() # List containing all the matrices
sage: len(Mlist)
81


As for your function, it is also not correct, unless you have copy-pasted incorrectly.

1. First, the indentation in the function is wrong.
2. Secondly, you need not define UT to be a symbolic variable because you are redefining UT to be a list.
3. Thirdly, you are not returning anything from the function, so I don't know whether your function is incomplete, or this is what you intended.
more

def ListM(p):
UT=[]
for i1 in range(p):
for i2 in range(p):
for i3 in range(p):
for i4 in range(p):
UT=UT+[matrix([[i1,i2],[i3,i4]])]
return UT


Note that output of ListM(3) looks ugly, but this is a formatting "bug" when you display such a list, output is correct.

Python has very nice syntax for "list comprehensions", you may write:

def rows(p):
return [[x,y] for x in range(p) for y in range(p)]
def ListM(p):
return [matrix([r1,r2]) for r1 in rows(p) for r2 in rows(p)]


Of course in this case using MatrixSpace(GF(p),2,2) is definitely the right solution. Good luck with Sage !

more

## Stats

Seen: 589 times

Last updated: Mar 24 '13