Ask Your Question
1

Pulling the index of an entry of a matrix

asked 2013-05-21 05:18:11 -0500

JoshIzzard gravatar image

Let $M$ be some matrix, then I am looking for how to find out which entries of $M$ make the statement M[i,j] == 25 true. Specifically, this is the code I'm using to generate the matrix, called deg:

deg = matrix(ZZ, 15)
A = lambda i: WeylCharacterRing("A{0}".format(i), style = "coroots")
for i in range(1,15):
    fw = A(i).fundamental_weights()
    for j in range(1,len(fw)):
        deg[i,j] = A(i)(fw[j]).degree()


print deg

It works great, but now instead of printing deg and finding the entries manually, I would like to be able to store which entries [i,j] of deg are equal to 25 in some list, and then print that list, which would ideally look something like:

list(tfentry)
{ (2,3), (4,4) }

etc.

Any tips on where to look or help files to examine?

Thanks very much.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2013-05-21 06:44:30 -0500

niles gravatar image

One way you could do this is to use a conditional list comprehension; these take the form

[x for x in list if <condition>]

And since you will be iterating over a matrix, a double list comprehension is in order; these take the form

[x for b in a for x in b]

where a is the "outer list", and b is the "inner list". And since you want to know the indices and the entries together, we'll use the enumerate function. So here's a conditional double list comprehension which returns (i,j) such that deg(i,j) == 15:

sage: [(i,j) for (i,deg_i) in enumerate(deg) for (j,deg_ij) in enumerate(deg_i) if deg_ij == 15]
[(5, 2), (5, 4), (14, 1)]

Another Sage-specific data type that might interest you is sets -- these are like lists, but automatically condense duplicate entries. For example, the set of values in the matrix deg can be given by

sage: deg_values = set([x for row in deg for x in row])
sage: len(deg_values)
52
edit flag offensive delete link more

Comments

Thanks very much for the help @niles, this should work well.

JoshIzzard gravatar imageJoshIzzard ( 2013-05-21 08:24:34 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-05-21 05:18:11 -0500

Seen: 85 times

Last updated: May 21 '13