Ask Your Question
1

Count number of ones in a set of matrix [closed]

asked 2019-02-25 03:15:10 +0100

imnvsh gravatar image

I am having the following code:

v = MatrixSpace(GF(2),2,2)
c = [0]*2
for vv in v.list():
    t=sum(vv)
    c = [x+y for x,y in zip(c,t)]
    print c

My goal is to count how many '1s' that I have for each column within the set of matrices. For example with the first 4 matrices in the set:

[0 0]  [1 0]  [0 1]  [0 0] 
[0 0], [0 0], [0 0], [1 0]

I expect to receive [2,1] as a result, i.e. there are 2 of '1s' appear in the 1st column and 1 of '1s' appears in the 2nd column. However, I got [0, 1], because it's binary base.

Thank you for reading my problem and support :)

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by imnvsh
close date 2019-03-01 11:28:18.279600

Comments

Use x.lift()+y.lift()

FrédéricC gravatar imageFrédéricC ( 2019-02-25 09:31:04 +0100 )edit

2 Answers

Sort by » oldest newest most voted
1

answered 2019-02-25 11:14:53 +0100

slelievre gravatar image

Building on @FrédéricC's comment.

If a is an element in GF(2), a.lift() is the corresponding element in ZZ. Using .lift() makes it so that 1 + 1 will be computed in ZZ and give 2 instead of being computed in GF(2) and give 0.

If a is a matrix over GF(2), a.lift() is the corresponding matrix over ZZ.

The rows of a can be summed using sum(a).

Define the matrix space:

sage: M = MatrixSpace(GF(2), 2, 2)

List its elements:

sage: M.list()
[
[0 0]  [1 0]  [0 1]  [0 0]  [0 0]  [1 1]  [1 0]  [1 0]
[0 0], [0 0], [0 0], [1 0], [0 1], [0 0], [1 0], [0 1],

[0 1]  [0 1]  [0 0]  [1 1]  [1 1]  [1 0]  [0 1]  [1 1]
[1 0], [0 1], [1 1], [1 0], [0 1], [1 1], [1 1], [1 1]
]

How many 1's in each column of each matrix in M:

sage: [sum(a.lift()) for a in M]
[(0, 0),
 (1, 0),
 (0, 1),
 (1, 0),
 (0, 1),
 (1, 1),
 (2, 0),
 (1, 1),
 (1, 1),
 (0, 2),
 (1, 1),
 (2, 1),
 (1, 2),
 (2, 1),
 (1, 2),
 (2, 2)]

Sum over all matrices in M:

sage: sum(sum(a.lift()) for a in M)
(16, 16)
edit flag offensive delete link more
2

answered 2019-02-25 10:56:57 +0100

rburing gravatar image

updated 2019-02-25 11:00:11 +0100

As mentioned in the comments you can do a lift.

For vectors you can also change the ring to the integers, to lift all the entries. For example,

def ones_per_column(matrices):
    return sum(vector(sum(c.change_ring(ZZ)) for c in m.columns()) for m in matrices)

Maybe more efficiently, change the ring of each matrix to the integers, add them and take the column sums:

def ones_per_column(matrices):
    return vector(sum(c) for c in sum(m.change_ring(ZZ) for m in matrices).columns())

In either case you can do

sage: ones_per_column(list(MatrixSpace(GF(2), 2, 2))[0:4])
(2, 1)
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2019-02-25 03:15:10 +0100

Seen: 1,260 times

Last updated: Feb 25 '19